1.json_encode () Chinese returned as null in gbk/gb2312
The code is as follows |
|
$arr = Array ( Array ( ' CatID ' => ' 4 ', ' CatName ' => ' www.111cn.net ', ' Meta_title ' => ' A tutorial Network 2 ' ) );
echo Json_encode ($arr); Results [{"CatID": "4", "CatName": "Www.111cn.net", "Meta_title": null}] |
Have a look at it? "Meta_title": null he would have been a value for a tutorial network 2, this we checked the principle is json_encode only support uft-8 encoding, we convert
The code is as follows |
|
<?php $data = "JSON Chinese"; $newData =iconv ("Gb2312″, Utf-8//ignore", $data); Echo $newData; Ignore means ignoring the conversion error, and if there is no ignore argument, all characters after that character will not be saved. or ("Gb2312″," Utf-8″, $data); ?> |
Step2
The Background PHP page (page encoding is UTF-8 or has converted the characters to UTF-8) uses Json_encode to convert the array arrays in PHP into JSON strings. For example:
The code is as follows |
|
<?php $testJSON =array (' name ' => ' Chinese string ', ' value ' => ' test '); echo Json_encode ($testJSON); ?> View the output as: {' name ': ' U4e2du6587u5b57u7b26u4e32″, ' value ': ' Test '} |
Visible is the use of UTF8 encoded characters, the use of Json_encode also appeared in Chinese garbled. The solution is to use the Json_encode before using the function UrlEncode (), and then Json_encode, the output of the results in the function UrlDecode () back. as follows:
The code is 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)); ?> View the output as: {' name ': ' Chinese string ', ' value ': ' Test '} |
Summary: Json_encode function can only handle UFT8 string, if it is in Chinese is not good for byte processing, because the Chinese GBK and uft length is not the same oh, this I do not in-depth introduction.