If you call the json_encode () function that comes with PHP, when you encounter a Chinese character, the Chinese character will be escaped. For example:
Echo json_encode (array (' '));
// Output: ["\ u4f60 \ u597d"]
This is very annoying, like a bunch of garbled characters. The JSON standard never says that non-ASCII characters should be escaped. The standard is "Any UNICODE character ".
How Can I disable this escape? The answer is: PHP's built-in json_encode () cannot disable this feature (you can add the JSON_UNESCAPED_UNICODE option for later versions before version 5.4.0). You can only change to a new JSON Library. for simplicity, I wrote dozens of lines of code to implement a json_encode ().
| The code is as follows: |
Copy code |
Class Util
{
Static function json_encode ($ input ){
// This option has been added since PHP 5.4.0.
If (defined ('json _ UNESCAPED_UNICODE ')){
Return json_encode ($ input, JSON_UNESCAPED_UNICODE );
}
If (is_string ($ input )){
$ Text = $ input;
$ Text = str_replace ('\\',' \\\\ ', $ text );
$ Text = str_replace (
Array ("\ r", "\ n", "\ t ","\""),
Array ('\ r',' \ n', '\ t ','\\"'),
$ Text );
Return '"'. $ text .'"';
} Else if (is_array ($ input) | is_object ($ input )){
$ Arr = array ();
$ Is_obj = is_object ($ input) | (array_keys ($ input )! = Range (0, count ($ input)-1 ));
Foreach ($ input as $ k = & gt; $ v ){
If ($ is_obj ){
$ Arr [] = self: json_encode ($ k). ':'. self: json_encode ($ v );
} Else {
$ Arr [] = self: json_encode ($ v );
}
}
If ($ is_obj ){
Return '{'. join (',', $ arr ).'}';
} Else {
Return '['. join (',', $ arr). ']';
}
} Else {
Return $ input .'';
}
}
}
|
I cannot think about it, for example, judging the location of the correlated array (is_obj). If you don't like the class, convert it to a pure function and change the name.