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:
// 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);
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3