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, 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:
<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!