Solve Chinese transcoding and garbled characters in phpjson_encode.
When PHP's json_encode is used to process Chinese characters, Chinese characters will be encoded and become unreadable, similar to the "\ u" format. if you want Chinese characters not to be transcoded, three methods are provided:
1. upgrade PHP. in PHP5.4, this problem was finally solved. Json added an option: JSON_UNESCAPED_UNICODE, so the name is Unicode, that is, Json does not encode Unicode.
Echo json_encode ("Chinese", JSON_UNESCAPED_UNICODE );
// "Chinese"
2. urlencode the Chinese characters first and then use json_encode. after json_encode, use urldecode again to decode them. in this way, the encoded Chinese characters in the json Array will not undergo unicode encoding.
$ Array = array (
'Test' => urlencode ("I'm a test ")
);
$ Array = json_encode ($ array );
Echo urldecode ($ array );
// {"Test": "I'm a test "}
3. decodes the unicode code. the decoding function is as follows:
Function decodeUnicode ($ str)
{
Return preg_replace_callback ('/\\\\ u ([09af] {4})/I ',
Create_function (
'$ Matches ',
'Return mb_convert_encoding (pack ("H", $ matches [1]), "UTF8", "UCS2BE ");'
),
$ Str );
}
// Prevents Chinese json transcoding
Function jsonEncodeWithCN ($ data ){
Return preg_replace ("// \ u ([09af] {4})/ie", "iconv ('ucs2be', 'utf8', pack ('h4 ', '$ 1') ", json_encode ($ data ));
}
$ Arr = array ('a' => 'test', B => 'Hello ');
Echo jsonEncodeWithCN ($ arr );