JSON Encoding Issues with PHP Arrays
Question:
I am using PHP's json_encode() function to convert MySQL table data into JSON, but I'm encountering strange behavior. The function doesn't encode data for certain queries, specifically those containing special characters or certain continent codes.
Code Snippet:
<code class="php">$result = mysqli_query($con, "SELECT * FROM countries WHERE continent_code='EU'") or die(mysqli_error($con)); while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { $orders[] = array( 'CountryCode' => $row['code'], 'CountryName' => $row['name'] ); } echo json_encode($orders);</code>
Observation:
Problem:
The json_encode() function requires all incoming data to be UTF-8 encoded. Special characters and certain continent codes may not be properly encoded in the database or during data manipulation.
Solution:
Ensure UTF-8 encoding throughout your web application. This includes:
As the RFC4627 states: "JSON text SHALL be encoded in Unicode. The default encoding is UTF-8." By ensuring UTF-8 encoding, json_encode() will be able to correctly process all data, regardless of its content.
The above is the detailed content of Why Does `json_encode()` Fail with Specific Continent Codes in PHP?. For more information, please follow other related articles on the PHP Chinese website!