This article describes how to solve the problem of json_encode processing gbk and gb2312 Chinese garbled characters in php. For more information, see
This article describes how to solve the problem of json_encode processing gbk and gb2312 Chinese garbled characters in php. For more information, see
This article describes how to solve the problem of json_encode processing gbk and gb2312 Chinese garbled characters in php. The specific method is as follows:
1. json_encode () returns null for Chinese in gbk/gb2312
$ Arr = array ('catid' => '4', 'catname' => 'www .jb51.net', 'meta _ title' => 'feet home ')); echo json_encode ($ arr );
Running result:
[{"Catid": "4", "catname": "www.jb51.net", "meta_title": null}]
Take a look at it "meta_title": null he was originally a value for "feet home", this we checked the principle is json_encode only supports uft-8 encoding, we convert
<? Php $ data = "JSON Chinese"; $ newData = iconv ("GB2312", "UTF-8 // IGNORE", $ data); echo $ newData; // ignore indicates that the conversion error is ignored. Without the ignore parameter, all characters after this character will not be saved. // Or ("GB2312", "UTF-8", $ data);?>
2. The background PHP page (the page is encoded as a 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:
<? Php $ 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 the urldecode () function to return the output results. The details are as follows:
<? Php $ testJSON = array ('name' => 'Chinese string', 'value' => 'test'); // 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": "test "}
Summary: The json_encode function can only process uft8 strings. If it is a Chinese character, it is difficult to process the bytes because the length of the Chinese gbk is different from that of the uft.