Home > Database > Mysql Tutorial > body text

How to Encode UTF-8 Characters Correctly with json_encode() in PHP?

Mary-Kate Olsen
Release: 2024-10-30 16:28:03
Original
608 people have browsed it

How to Encode UTF-8 Characters Correctly with json_encode() in PHP?

UTF-8 Character Encoding Encoding Issues with json_encode()

Problem Statement

Encoding UTF-8 characters is problematic with the json_encode() function. After this function encodes values from LATIN1 to UTF-8, the output becomes null.

Question

How can json_encode() be used to encode UTF-8 values correctly, without resorting to third-party libraries like Zend Framework?

Answer

To resolve this issue, follow these steps:

  1. Create an Empty Array: Initialize an empty $rows array to store the encoded result set.
  2. Encode Row Values: Iterate through the database result set, converting each row's values to UTF-8 using utf8_encode. Store the encoded rows in the $rows array.
  3. Encode and Echo JSON: Finally, pass the $rows array to json_encode() and echo the result to send the correctly encoded UTF-8 values to the web browser.

Here's an example code snippet:

<code class="php">// Create an empty array for the encoded resultset
$rows = array();

// Loop over the db resultset and put encoded values into $rows
while($row = mysql_fetch_assoc($result)) {
  $rows[] = array_map('utf8_encode', $row);
}

// Output $rows
echo json_encode($rows);</code>
Copy after login

The above is the detailed content of How to Encode UTF-8 Characters Correctly with json_encode() in PHP?. 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