PHP json_encode Chinese is transcoded problem

Source: Internet
Author: User

When you do Json_encode in php5.2. Chinese will be Unicode encoded,
php5.3 added the options parameter,
After 5.4 Join Json_unescaped_unicode, this parameter, do not need to do escape and UNICODE processing.
So we need to do a deal on Chinese before 5.4.
5.4 The inside of the treatment

PHP code
    1. Json_encode ( $str, Json_unescaped_unicode);

      Before 5.4, there are two ways to handle
      Method 1.
      PHP code
        1. function Encode_json ($str) {
        2. $code = Json_encode ($str);
        3. return Preg_replace ("#\\\u ([0-9a-f]+) #ie", "iconv (' UCS-2 ', ' UTF-8 ', pack (' H4 ', ' \\1 '))", $code);
        4. }

      Method 1. In practical application there is a problem, some characters will be dropped, more than why, such as String: "Date 11.2" will be changed to "date." 2 "

      Method 2.
      First to deal with the need to do urlencode processing, and then Json_encode, and finally do urldecode processing
      PHP code
        1. function Encode_json ($str) {
        2. return UrlDecode (Json_encode (Url_encode ($str)));
        3. }
        4. /**
        5. *
        6. */
        7. function Url_encode ($str) {
        8. if (is_array ($str)) {
        9. foreach ($str as $key = =$value) {
        10. $str [UrlEncode ($key)] = Url_encode ($value);
        11. }
        12. } Else {
        13. $str = UrlEncode ($str);
        14. }
        15. return $str;
        16. }

PHP json_encode Chinese is transcoded problem

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.