How does json_encode prevent conversion of Chinese characters into unicode and json_encodeunicode?

Source: Internet
Author: User

How does json_encode prevent conversion of Chinese characters into unicode and json_encodeunicode?

As we all know, json_encode usually converts Chinese Characters in json to unicode, but this is not necessarily what we want. Sometimes, we need to obtain a json string in the Chinese character format, such as a json string encoded in gbk format (you only need to transcode the string in the Chinese character format ). Is there any good way?

Php officially heard this requirement and provided a reliable solution: JSON_UNESCAPED_UNICODE. This parameter ensures that json_encode no longer converts Chinese characters to unicode.

Does this seem to be solved? When we happily use this parameter, we find that there is no such thing. This parameter is only supported by php after 5.4. What should we do in the early stage of 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 are being "hidden" from normal json_encoding3 array_walk_recursive ($ arr, function (& $ item, $ key) {if (is_string ($ item )) $ item = mb_encode_numericentity ($ item, array (0x80, 0 xffff, 0, 0 xffff), 'utf-8 ');}); 4 return mb_decode_numericentity (json_encode ($ arr), array (0x80, 0 xffff, 0, 0 xffff), 'utf-8'); 5}

However, this method is only supported by 5.3, because 5.2 does not support anonymous functions. As for the solution? Define an anonymous function.

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.