Home  >  Article  >  Backend Development  >  How to Encode UTF-8 Characters in PHP JSON Output without Unicode Escaping?

How to Encode UTF-8 Characters in PHP JSON Output without Unicode Escaping?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 20:51:03277browse

How to Encode UTF-8 Characters in PHP JSON Output without Unicode Escaping?

Preserving UTF-8 in PHP JSON Output

Question:

How can you prevent PHP's json_encode function from escaping non-ASCII characters as Unicode sequences? The desired output is UTF-8 encoded characters, not unicode sequences. For example, an array containing the value "á" should be encoded as {"a":"á"}, not {"a":"u00e1"}.

Answer:

While the JSON specification allows for both encoding formats, {"a":"u00e1"} and {"a":"á"} are treated equally by JSON decoders.

For PHP versions 5.4 and above, json_encode provides the JSON_UNESCAPED_UNICODE option. This option outputs plain UTF-8 encoded characters without escaping.

<code class="php">$json = json_encode($arr, JSON_UNESCAPED_UNICODE);</code>

For older PHP versions, consider the following options:

  • Custom JSON Encoder: Implement a custom JSON encoder that omits character escaping for non-ASCII characters.
  • Pear's JSON Encoder: Modify the Pear JSON encoder by removing lines 349 to 433. This section contains the escaping logic.

The above is the detailed content of How to Encode UTF-8 Characters in PHP JSON Output without Unicode Escaping?. 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