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

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

Linda Hamilton
Linda HamiltonOriginal
2024-10-31 03:42:30242browse

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

How to Encode JSON in UTF-8 Without Escaping Unicode Characters

In PHP, the json_encode() function converts values into JSON strings by default, however, it escapes Unicode characters into their Unicode code point representation. This can be undesirable in certain scenarios where the output requires UTF-8 encoding instead of Unicode encodings.

Consider the following example:

<code class="php">$arr = ['a' => 'á'];
echo json_encode($arr);</code>

The expected output is "a": "á", but the actual result is {"a":"u00e1"}. This is because the json_encode() function has encoded the character 'á' into its Unicode code point representation, which is "u00e1".

Solution:

While there is no built-in option in PHP versions prior to 5.4 to disable Unicode escaping in json_encode(), there are a few workarounds to achieve this:

  1. Roll Your Own JSON Encoder: Create a custom JSON encoder that does not encode non-ASCII characters.
  2. Use Pear's JSON Encoder: Use the Pear JSON encoder and remove lines 349 to 433, which are responsible for Unicode escaping.
  3. Utilize PHP 5.4 : In PHP 5.4 and later versions, the json_encode() function provides a JSON_UNESCAPED_UNICODE option that allows for plain output without Unicode escaping. Here's an example using this option:
<code class="php"><?php
header('Content-Type: application/json');
$arr = ['a' => 'á'];
echo json_encode($arr, JSON_UNESCAPED_UNICODE);
?></code>

This will output the desired JSON string: "a": "á".

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