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 json_encode
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. the code is as follows:
- $./Php/bin/php-r 'echo json_encode ("Chinese ");'
- "U4e2du6587"
Reduced readability, the latest php 5.4 json_encode supports the UTF-8 encoding, can put the Chinese do not encode the direct output, then the lower version how to do? There are also ways to encapsulate a function and share it with you. the code is as follows:
- 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 ));
- }
For example, using another solution, the background PHP page (page code as UTF-8 or has converted the character into a UTF-8) using json_encode to convert the array in PHP into a JSON string, for example:
-
- $ TestJSON = array ('name' => '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 output result using the urldecode () function. The details are as follows:
-
- $ TestJSON = array ('name' => 'Chinese string', 'value' => 'Www .phpfensi.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.111cn.net "}
At this point, Chinese characters are successfully output.