This example describes a workaround for PHP that does not escape Chinese when using the Json_encode function. Share to everyone for your reference. The specific methods are as follows:
Json_encode function for GBK in the Chinese character is not converted or directly converted to a space, this article to give you a word about JSON does not escape the problem-handling skills, I believe it is helpful to everyone.
If you call PHP's Json_encode () function, the Chinese will be escaped when you encounter Chinese. For example:
Copy Code code as follows:
echo json_encode (Array (' Hello '));
Output: ["\u4f60\u597d"]
This is very annoying, like a bunch of garbled, JSON Standard never said to put non-ASCII character escape, the standard is said to be "any UNICODE character".
How do you disable this escape? The answer is that PHP's Json_encode () cannot disable this feature (before the 5.4.0 version, you can add the Json_unescaped_unicode option), you can only change to a new JSON library. For simplicity, I wrote dozens of lines of code, Implement a Json_encode ().
Copy Code code as follows:
Class Util
{
static function Json_encode ($input) {
This option is added from 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 => $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. '';
}
}
}
Places that are not considered, such as determining the associative array (is_obj), are confronted with problems. If you don't like the class, turn yourself into a pure function and change your name.
I hope this article will help you with your PHP program design.