Php5.2 Json cannot properly handle Chinese and GB encoding Solutions

Source: Internet
Author: User

The json function added by php5.2 is very popular, but it has been tested and found that,
Json_encode is problematic in processing Chinese characters,
1. Cannot process the GB encoding. All the GB encoding will be replaced with null characters.
2. UTF-8 encoded Chinese characters are encoded as unicode, which is equivalent to the processing result of the javascript escape function.
Copy codeThe Code is as follows:
/*

In order to use json correctly, we should first adopt utf8 encoding in encoding, and then slightly process the returned results of json_encode to get the correct results.
I wrote a simple class and wrapped the two functions,
**/
Class Json {
Public static function encode ($ str ){
$ Code = json_encode ($ str );
Return preg_replace ("# \\\ u ([0-9a-f] +) # ie", "iconv ('ucos-2', 'utf-8', pack ('h4 ', '\ 1') ", $ code );
}

Public static function decode ($ str ){
Return json_decode ($ str );
}
}
// When using

Json: encode ($ code );
Json: decode ($ code );
/** In this way, utf8 Encoded chinese characters can be correctly processed.

PS: for Chinese Characters in GB encoding, we can convert them into UTF8 encoding Before encoding. During decoding, we can convert them into utf8-> gb.
In addition, the result of json_encode is generally returned to the client for use. In fact, we can also use the javascript unescape function to decode the unicode-Encoded chinese characters to restore them to the correct Chinese characters.

Alternatively, use: $ title = mb_convert_encoding ($ title, 'html-ENTITIES ', $ this-> _ outCharset). // The data is normally displayed under any encoding.
********/

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.