php5.2 JSON does not correctly handle Chinese, GB-encoded solutions

Source: Internet
Author: User
Tags json

 json_encode to Chinese processing is a problem, not processing GB encoding, all GB code will be replaced with empty characters, there is a good solution, you can refer to the following

php5.2 's new JSON feature is very popular, but tests have found that,  Json_encode has a problem with Chinese processing,  1. GB encoding cannot be processed, and all GB encodings are replaced with the null character .  2. UTF8 encoded Chinese is encoded into Unicode encoding, equivalent to the result of the JavaScript escape function processing .  code as follows:/*    in order to use JSON correctly, we should first use UTF8 encoding on the code, Then we can get the correct result by slightly processing the return result of the Json_encode.   I've written a simple class that wraps the two functions,  **/  class json{  public static function encode ($STR) {  $code = Json_e Ncode ($STR);  return Preg_replace ("#u ([0-9a-f]+) #ie", "Iconv (' UCS-2 ', ' UTF-8 ', pack (' H4 ', ' 1 '))", $code); }     public static function decode ($STR) {  return Json_decode ($str); } } //When used   &N Bsp Json::encode ($code);  Json::d ecode ($code); /** This will correctly handle UTF8 encoded Chinese.     PS: for GB-encoded Chinese, we can be encoded in the first UTF8 encoding, and then coding, decoding the time to do a UTF8-> GB conversion on it.   Other general Json_encode results we are back to the client to use, we can actually use the JavaScript unescape function to decode the Unicode encoded Chinese, so as to restore the correct Chinese.     or used: $title = mb_convert_encoding ($title, ' html-entities ', $this->_outcharset);//Normal display   * * * /&nbSp  

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.