Json_encode gbk/gb2312 Chinese garbled characters in php
1. json_encode () Chinese returns null in gbk/gb2312 Chinese
| The Code is as follows: |
|
|
$ Arr = array (
Array (
'Catid' => '4 ',
'Catname' => 'www .111cn.net ',
'Meta _ title' => 'one-click tutorial network 2'
)
);
Echo json_encode ($ arr );
Result
[{"Catid": "4", "catname": "www.111cn.net", "meta_title": null}] |
Take a look at it "meta_title": null he was originally a value for a poly tutorial Network 2, this we checked the principle is json_encode only supports uft-8 encoding, we convert
| The Code is as follows: |
|
<? 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 );
?> |
Step 2
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:
| The Code is as follows: |
|
<? 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 json_encode to return the urldecode () function when outputting the results. The details are 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 ));
?>
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. I will not go into details here.