When I use php json_encode(), there is no problem if it is in English or numbers, but when I use Chinese, unrecognizable Chinese garbled characters appear. Let’s see how I solve the Chinese garbled characters in json_encode.
Find a solution online:
代码如下 | 复制代码 |
/* 处理json_encode中文乱码 */ $data = array ('game' => '冰火国度', 'name' => '刺之灵', 'country' => '冰霜国', 'level' => 45 ); echo json_encode ( $data ); echo " "; $newData = array (); foreach ( $data as $key => $value ) { $newData [$key] = urlencode ( $value ); } echo urldecode ( json_encode ( $newData ) ); ?> |
Later I asked others for advice and found that base64 encoding can also be used, but base64 encoding cannot be placed in the URL. Baidu explained this:
Standard Base64 is not suitable for transmission directly in the URL, because the URL encoder will change the "/" and "+" characters in standard Base64 into the form of "%XX", and these "%" The number needs to be converted when it is stored in the database, because the "%" sign has been used as a wildcard character in ANSI SQL.
However, my data is sent via POST and is not in the HTTP head, but in the message-body, so it is not affected.
json_encode can only accept data in utf-8 format
For example: 'Xu' becomes 'u80e5' after json_encode processing, and the Chinese part of the final json is replaced with unicode encoding. What we have to solve is to convert the object into json and ensure that the Chinese inside the object still appears as normal Chinese in json. Now it seems that only using json_encode cannot achieve the goal.
My solution: first url-encode the Chinese field in the class (urlencode), then json-encode the object (jsonencode), and finally url-decode (urldecode) the json, which is the final json. The Chinese inside is still the same Chinese !
The test code is as follows:
The code is as follows
|
Copy code
|
||||
代码如下 | 复制代码 | ||||
{"item1":1,"item2":"u4e2du6587"} {"item1":1,"item2":"中文"} {"item1":1,"item2":"u4e2du6587"} "u80e5" |
The code is as follows | Copy code |
{"item1":1,"item2" :"u4e2du6587"} {"item1":1,"item2":"中文"} {"item1":1,"item2":"u4e2du6587"} "u80e5" |