Solve Chinese transcoding and garbled characters in phpjson_encode.

Source: Internet
Author: User
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 );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.