php5.2 JSON does not correctly handle Chinese, GB-encoded Solutions _php Tutorial

Source: Internet
Author: User
php5.2 's new JSON functionality is very popular, but it has been tested and found
Json_encode's handling of Chinese is problematic,
1. GB encoding cannot be processed, all GB encodings are replaced with null characters.
2.UTF8 encoded in Chinese is encoded as Unicode encoding, which is equivalent to the result of JavaScript's escape function processing.
Copy CodeThe code is as follows:
/*

In order to use JSON correctly, we should first use UTF8 encoding on the code, and then we can get the correct result with a little processing of the return result of Json_encode.
I've written a simple class that wraps the two functions,
**/
Class json{
public static function encode ($STR) {
$code = Json_encode ($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 using the

Json::encode ($code);
Json::d ecode ($code);
/** This can correctly handle the UTF8 encoded in Chinese.

PS: For GB encoding of Chinese, we can encode the first to UTF8 encoding, and then encode, decoding the time to do a utf8-to-GB conversion can be.
In addition to the general Json_encode results we return to the client to use, we can actually use the JavaScript unescape function to decode the Unicode encoding of Chinese, so as to restore the correct Chinese.

or with: $title = mb_convert_encoding ($title, ' html-entities ', $this->_outcharset);//normal display under any encoding
********/

http://www.bkjia.com/PHPjc/746869.html www.bkjia.com true http://www.bkjia.com/PHPjc/746869.html techarticle php5.2 New JSON feature is very popular, but after testing found that the processing of Chinese json_encode is problematic, 1. GB encoding cannot be processed, all GB encoding will be replaced with empty ...

  • Related Article

    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.