Home > Database > Mysql Tutorial > body text

Why Does json_encode() Fail To Encode Accented Characters From a MySQL Database with Latin1 Encoding?

Barbara Streisand
Release: 2024-10-30 11:55:02
Original
335 people have browsed it

Why Does json_encode() Fail To Encode Accented Characters From a MySQL Database with Latin1 Encoding?

JSON Encoding Struggles with UTF-8 Characters in MySQL

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!