The json_encode function cannot perform the same operations on Chinese characters. If it is uft8, it will convert Chinese characters to u590fu5a03u7684u8bf1u60d. How can we output them to Chinese Characters? Let's take a look. The json_encode function cannot perform the same operations on Chinese characters. If it is uft8, it will convert Chinese characters to u590fu5a03u7684u8bf1u60d. How can we output them to Chinese Characters? Let's take a look.
Script ec (2); script
Recently, json_encode was used to convert the array into json data and store it in the database. because the length of the field is not determined, this method can only be used. However, after json_decode is parsed as an array, but there is a class
Like "u590fu5a03u7684u8bf1u60d14u5979u7684u6280u5de7", by querying Baidu, this should be a UCS-2 encoded string, so how to convert this string?
In fact, when json_encode conversion is performed in versions earlier than php5.2. The Chinese language is unicode encoded. The options parameter is added to php5.3 and JSON_UNESCAPED_UNICODE is added after 5.4. This parameter does not need to be processed by escape or unicode. Therefore, we need to process Chinese before 5.4.
Processing in php5.4
json_encode($str, JSON_UNESCAPED_UNICODE);
There are two ways to deal with php5.4
Method 1
function encode_json($str){ return preg_replace("/u([0-9a-f]+)/ie", "iconv('UCS-2', 'UTF-8', pack('H4', '\\1'))", $code); }
There is a problem in actual application. Some characters will drop, not just why, such as the string: "date 11.2" will be changed to "date. 2 ″.
Method 2
function encode_json($str) { return urldecode(json_encode(url_encode($str))); }function url_encode($str) { if(is_array($str)) { foreach($str as $key=>$value) { $str[urlencode($key)] = url_encode($value); } } else { $str = urlencode($str); } return $str; }
This site uses a virtual host, so you cannot modify the php version. Therefore, you can only use the first method, but the method is indeed effective.
Method 3 function decodeUnicode ($ str) {return preg_replace_callback ('/\\\\ u ([0-9a-f] {4})/I', create_function ('$ matches ', 'Return mb_convert_encoding (pack ("H *", $ matches [1]), "UTF-8", "UCS-2BE"); '), $ str );}