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 has Chinese, using the Json_encode function to be processed after the character is encoded into Unicode, How can I display Chinese in JSON? Please see below.
First, let's introduce 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 ' => ' yard farmer Hello! ');
$json = Json_encode ($arr);
echo $json;
? >
The results of the output are:
{"P1": "Ni\" Hao "," P2 ": 2," ch ":" \u7801\u519c\u4f60\u597d\uff01 "}
Here to note:
Double quotes are automatically encoded as \ In JSON, which is very well understood, in the string in JS is not allowed to come out single quotes, double quotes and back slashes.
Chinese characters are encoded as Unicode
If it is a write interface, then the direct output is enough, Chinese do not have to do processing. Wait until the client, then to the Unicode of Chinese into Chinese characters can be. But if you want to output the characters directly on the server side, we can do the following.
<?php
$arr = Array (' p1 ' => ' Nihao ', ' P2 ' =>2, ' ch ' => ' yard farmer 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 ":" Yard farmer Hello! " "}
This operation is very simple, in fact, is to match the output results, the Unicode restore to the Chinese characters.
Thank you for reading, I hope to help you, thank you for your support for this site!