PHP 5.4 or earlier versions of json do not support the solution of Chinese without escaping content
This article mainly introduces the solution that php 5.4 and earlier versions of json do not support Chinese characters without escaping content. Using a custom php method to simulate joson Chinese characters without escaping, it has some reference value, for more information, see
This example describes how to solve the problem that json versions earlier than php5.4 do not support Chinese characters without escaping content. Share it with you for your reference. The specific analysis is as follows:
When writing the ERP interface, the JAVA side receives the content after json_encode.
The Code is as follows:
{"OrderCode": "1401160935542399", "creator": "\ u751f \ u6d3b \ u7528 \ u54c1 \ u6d4b \ u8bd5 \ u5c0f \ u5c4b "}
"Creator": "\ u751f \ u6d3b \ u7528 \ u54c1 \ u6d4b \ u8bd5 \ u5c0f \ u5c4b" is in Chinese, and UTF8 is used currently. However, when the JAVA party receives such requests, it automatically converts the escaped Chinese characters back to the Chinese ones. The signature calculation method is based on this, and the signature is naturally not correct.
I checked the PHP Manual. The PHP version below 5.4 cannot escape Chinese characters, but the PHP version on our server is 5.3. So I used PHP to simulate a JSON method.
The Code is as follows:
// Simulate joson without escaping
If (version_compare (PHP_VERSION, '5. 4.0 ')> = 0 ){
Function json_encode_ex ($ var ){
Return json_encode ($ var, JSON_UNESCAPED_UNICODE );
}
} Else {
Function json_encode_ex ($ var ){
If ($ var = null)
Return 'null ';
If ($ var = true)
Return 'true ';
If ($ var = false)
Return 'false ';
Static $ reps = array (
Array ("\", "/", "\ n", "\ t", "\ r", "\ B", "\ f ", '"',),
Array ('\', '\/', '\ n',' \ t', '\ R',' \ B ', '\ F ','\"',),
);
If (is_scalar ($ var ))
Return '"'. str_replace ($ reps [0], $ reps [1], (string) $ var ).'"';
If (! Is_array ($ var ))
Throw new Exception ('json encoder error! ');
$ IsMap = false;
$ I = 0;
Foreach (array_keys ($ var) as $ k ){
If (! Is_int ($ k) | $ I ++! = $ K ){
$ IsMap = true;
Break;
}
}
$ S = array ();
If ($ isMap ){
Foreach ($ var as $ k => $ v)
$ S [] = '"'. $ k. '":'. call_user_func (_ FUNCTION __, $ v );
Return '{'. implode (',', $ s ).'}';
} Else {
Foreach ($ var as $ v)
$ S [] = call_user_func (_ FUNCTION __, $ v );
Return '['. implode (',', $ s). ']';
}
}
}
You can use built-in functions directly. Json_encode_ex (array ('diaoyu island '=> 'China'); multi-dimensional arrays are also supported.
I hope this article will help you with php programming.