Home  >  Article  >  Database  >  How to Handle UTF-8 Characters When Encoding a PHP Array to JSON?

How to Handle UTF-8 Characters When Encoding a PHP Array to JSON?

Barbara Streisand
Barbara StreisandOriginal
2024-11-01 13:50:54897browse

How to Handle UTF-8 Characters When Encoding a PHP Array to JSON?

JSON Encoding Battles with UTF-8 Characters in PHP

In the realm of database handling in PHP, one may encounter challenges when working with accented characters and UTF-8 encoding. Consider the scenario where you wish to retrieve rows from a table that contains accented characters, and the column encoding is configured as latin1_swedish_ci.

Understanding the Problem

Attempts to display the fetched rows using utf8_encode() initially seem to work, but subsequent JSON encoding using json_encode() results in null values for the affected fields. This arises because json_encode() may not handle UTF-8 characters encoded using mysql_fetch_assoc().

A Solution to Preserve UTF-8

To resolve this issue, employ the following approach:

  1. Create an empty array named $rows to store the encoded results.
  2. Iterate over the database result set using while($row = mysql_fetch_assoc($result)).
  3. For each row, apply utf8_encode() to every element using $rows[] = array_map('utf8_encode', $row). This step properly converts accented characters to UTF-8.
  4. Finally, encode the $rows array to JSON using echo json_encode($rows).

By implementing this method, the JSON encoding will properly represent the UTF-8 characters, preserving the accented characters and preventing null values for the affected fields.

The above is the detailed content of How to Handle UTF-8 Characters When Encoding a PHP Array to JSON?. 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