Json_encode How to prevent Chinese characters from escaping into Unicode

Source: Internet
Author: User
As we all know, Json_encode usually escapes the characters in JSON into Unicode, but that's not necessarily what we want. Sometimes we need to get a JSON string in the form of a Chinese character, such as a JSON string that needs to be GBK encoded (as long as the character string is transcoded). Is there any good way?

PHP officially hears this demand and offers a reliable solution: Json_unescaped_unicode. This parameter ensures that Json_encode no longer converts Chinese characters to Unicode.

Does that seem to solve it? When we happily use this parameter, we find that there is no egg to use. In a closer look, this parameter is only supported by PHP after 5.4. What about the earlier PHP?

The community provides a solution:

1 function my_json_encode ($arr) {2//convmap since 0x80 char codes so it Takes all multibyte codes (above ASCII 127). So such characters is being "hidden" from normal json_encoding3array_walk_recursive($arr  function (&$item$keyif (is_string($item  $item = mb_encode_numericentity ($itemarray (0x80, 0xFFFF, 0, 0xFFFF), ' UTF-8 ' ); }); 4 return mb_decode_numericentity (Json_encode ($arrarray (0x80, 0xFFFF, 0, 0xFFFF), ' UTF-8 '); 5 }

However, this method is only supported in 5.3, since 5.2 does not support anonymous functions. As for the solution? Define the anonymous function as you please.

The above describes how Json_encode prevent Chinese characters from escaping into Unicode, including the contents of the content, I hope that the PHP tutorial interested in a friend helpful.

  • 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.