How to Encode Non-ASCII Characters in JSON with UTF-8 Using PHP\'s `json_encode`?

Linda Hamilton
Release: 2024-10-27 00:15:02
Original
148 people have browsed it

How to Encode Non-ASCII Characters in JSON with UTF-8 Using PHP's `json_encode`?

How to Return PHP json_encode with UTF-8 Encoding Instead of Unicode

When using PHP's json_encode function, by default, non-ASCII characters are encoded in Unicode format. This results in a JSON response with escape sequences like "u00e1" instead of UTF-8 encoded characters like "á".

Take this example:

<code class="php">$arr = array('a' => 'á');
echo json_encode($arr);</code>
Copy after login

The output would be:

<code class="json">{"a":"\u00e1"}</code>
Copy after login

To resolve this issue and return the JSON response with UTF-8 encoded characters, you can utilize the following approaches:

PHP 5.4 :

From PHP 5.4 onwards, json_encode provides the JSON_UNESCAPED_UNICODE option. By setting this option, non-ASCII characters will be plain UTF-8 encoded without escape sequences.

<code class="php">echo json_encode($arr, JSON_UNESCAPED_UNICODE);</code>
Copy after login

Older PHP Versions:

For versions prior to PHP 5.4, you can implement your own JSON encoder that omits encoding non-ASCII characters. Alternatively, you can utilize Pear's JSON encoder and remove lines 349 to 433 from the encoding function.

Please note that the difference between {"a":"u00e1"} and {"a":"á"} is purely how they are written in JSON syntax. Both representations will be decoded into the same Unicode value by JSON decoders.

The above is the detailed content of How to Encode Non-ASCII Characters in JSON with UTF-8 Using PHP\'s `json_encode`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!