Home >Database >Mysql Tutorial >Why Does json_encode() Fail To Encode Accented Characters From a MySQL Database with Latin1 Encoding?
When attempting to retrieve accented characters from a database with latin1_swedish_ci encoding and encode them into JSON using json_encode(), the result may be unexpected. The intended outcome, such as "Abord â Plouffe," is transformed into "null," rendering the encoded JSON invalid.
To resolve this issue, it is necessary to encode the retrieved values into UTF-8 explicitly before applying json_encode(). This ensures that the JSON output contains the correct UTF-8 characters and validates accordingly. Here is how to implement this solution:
<code class="php">// Initialize an empty array for the encoded result set $rows = array(); // Iterate over the PHPMyAdmin result set while ($row = mysql_fetch_assoc($result)) { // Apply UTF-8 encoding to each row value $rows[] = array_map('utf8_encode', $row); } // Output the encoded $rows echo json_encode($rows);</code>
In this modified code, we utilize the array_map function to apply utf8_encode to each element of every row in the result set. This ensures that all characters are properly encoded into UTF-8 before json_encode is executed. Consequently, the resulting JSON output will reflect the intended characters accurately, preserving the accented characters as desired.
The above is the detailed content of Why Does json_encode() Fail To Encode Accented Characters From a MySQL Database with Latin1 Encoding?. For more information, please follow other related articles on the PHP Chinese website!