PHP output JSON and display the Chinese characters in JSON
In PHP, we often need to output the array JSON, only need to use the Json_encode function to deal with the array, but sometimes the array is in Chinese, after the use of the Json_encode function is processed after the characters are encoded into Unicode, How can I display Chinese in JSON? Please see below.
First introduce the PHP output JSON format:
One of the simplest uses is to output the array directly as JSON, as follows:
<?php$arr = Array (' p1 ' = ' ni ' hao ', ' P2 ' =>2, ' ch ' = ' = ' yards farm Hello! $json = Json_encode ($arr); Echo $json; >
The result of the output is:
{"P1": "Ni\" Hao "," P2 ": 2," ch ":" \u7801\u519c\u4f60\u597d\uff01 "}
Here to note:
Double quotes are automatically encoded as \ "in JSON, which is a good understanding that the string in JS is not allowed in single quotes, double quotes, and backslashes.
Chinese characters are encoded as Unicode
If it is a write interface, then this output is sufficient, Chinese do not need to do processing. Wait until the client, and then go to the Unicode Chinese into Chinese characters can. But if we want to output the characters directly on the server side, we can do the following.
<?php$arr = Array (' p1 ' = ' = ' Nihao ', ' P2 ' =>2, ' ch ' = ' = ' Code farm Hello! $json = Json_encode ($arr); Echo Decodeunicode ($json); function Decodeunicode ($str) { return Preg_replace_callback ('/\\\\u ([0-9a-f]{4})/I ', create_function ( ' $matches ', ' Return mb_convert_encoding (Pack ("h*", $matches [1]), "UTF-8", "ucs-2be"); ' ), $str);}? >
Output:
{"P1": "Ni\" Hao "," P2 ": 2," ch ":" Yards nong Hello! " "}
This operation is very simple, actually is to match the output results, the Unicode reverted to the Chinese characters.
Thank you for reading, hope to help everyone, thank you for the support of this site!