Home  >  Article  >  Database  >  How to Encode UTF-8 Characters Correctly with json_encode() in PHP?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-30 16:28:03609browse

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>

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!

Statement:
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