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.