Decoding UTF-8 Strings in PHP Using json_encode
json_encode, a PHP function, converts Unicode characters to hexadecimal entities, leading to unexpected results when working with multiple languages. This behavior is designed to ensure compatibility with JSON standards.
To output UTF-8 characters instead, PHP provides the JSON_UNESCAPED_UNICODE option. This option can be applied to the json_encode function as follows:
<code class="php">$encodedData = json_encode($text, JSON_UNESCAPED_UNICODE);</code>
For example, the following code will output UTF-8 characters instead of hexadecimal entities:
<code class="php">$text = "База данни грешка."; $encodedData = json_encode($text, JSON_UNESCAPED_UNICODE); echo $encodedData; // Output: База данни грешка.</code>
By using the JSON_UNESCAPED_UNICODE option, you can ensure that UTF-8 characters are preserved when encoding data with json_encode, allowing for accurate language handling in your PHP applications.
The above is the detailed content of How to Output UTF-8 Characters in PHP Using json_encode?. For more information, please follow other related articles on the PHP Chinese website!