In the past, the most common problem was that the json_encode was garbled during gbk encoding. Today, we found that uft8 also had Chinese garbled characters. let's take a look at how to solve the problem. UTF-8 character json_encode is converted into utf16 encoding, also... in the past, the most common problem was that the json_encode was garbled during gbk encoding. Today, we found that uft8 also had Chinese garbled characters. let's take a look at how to solve the problem.
The UTF-8 character json_encode is converted into utf16 encoding, that is, the description:
$./Php/bin/php-r 'echo json_encode ("Chinese ");'
"U4e2du6587"
Reduced readability, json_encode of the latest php 5.4 supports UTF-8 encoding, which can directly output Chinese without encoding.
What about the lower version? There are also ways to encapsulate a function to share with you:
function my_json_encode($var) { return preg_replace("/u([a-f0-9]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode($var));}
To solve this problem.
The background PHP page (the page is encoded as a UTF-8 or has converted the character into a UTF-8) uses json_encode to convert the array in PHP into a JSON string. For example:
'Chinese string', 'value' => 'test'); echo json_encode ($ testJSON);?>
The output result is as follows:
{"name":"u4e2du6587u5b57u7b26u4e32","value":"test"}
It can be seen that UTF-8 characters are used, and Chinese garbled characters are also used in json_encode. The solution is to use the urlencode () function to process the characters before using json_encode, and then use json_encode to return the urldecode () function when outputting the results. The details are as follows:
'Chinese string', 'value' => 'Www .phprm.com '); // echo json_encode ($ testJSON); foreach ($ testJSON as $ key => $ value) {$ testJSON [$ key] = urlencode ($ value);} echo urldecode (json_encode ($ testJSON);?>
The output result is as follows:
{"Name": "Chinese string", "value": "www.phprm.com "}
At this point, Chinese characters are successfully output.
Address:
Reprinted at will, but please attach the article address :-)