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