php json_encode JSON_UNESCAPED_UNICODE

We know that when using PHP's json_encode to process Chinese, the Chinese will be encoded and become unreadable, similar to the "\ u ***" format, and it will also increase the amount
of data transferred to a certain extent. Don't add
it when writing, but when writing to the log, add it to facilitate direct viewing of Chinese

        header('Content-Type: application/json');
        echo json_encode($arrResponse);

        //返回值日志
        Bd_Log::addNotice('bcp_response', json_encode($arrResponse, JSON_UNESCAPED_UNICODE));
<?php
echo json_encode("中文"); //Output: "\u4e2d\u6587"
这就让我们这些在天朝做开发的同学, 很是头疼, 有的时候还不得不自己写json_encode.
?>

In PHP5.4, this problem was finally solved, and Json added an option: JSON_UNESCAPED_UNICODE, so the name is considered, that is, Json does not encode Unicode.

See the example below:

<?php
echo json_encode("中文", JSON_UNESCAPED_UNICODE); //Output: "中文"

How about it, does it make everyone very happy?

Oh, of course, Json also added in 5.4: JSON_BIGINT_AS_STRING, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES and other options, if you are interested, you can see: json_encode

There are 2 more commonly used parameters
JSON_UNESCAPED_UNICODE (Chinese does not convert to unicode, the corresponding number 256)
JSON_UNESCAPED_SLASHES (do not escape backslash, the corresponding number 64)

Usually only one constant can be passed in json_encode, what if two constants are used at the same time?

JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES = 320

How to use: json_encode ($ arr, 320); You can use 2 constants at the same time.

PHP5.4 only supports the parameter JSON_UNESCAPED_UNICODE. This parameter is to prevent Chinese characters from being escaped when json_encode, reducing the amount of data transmission. But in PHP5.3, you have to write a function to achieve it. The following is the solution:

/ **
* JSON encoding of array variables
* @param mixed array array to be encoded (other than resource type, it can be any data type, this function can only accept UTF-8 encoded data)
* @return string (return JSON form of array value)
* /
function json_encode ($ array)
{
if (version_compare (PHP_VERSION, '5.4.0', '<')) {
$ str = json_encode ($ array);
$ str = preg_replace_callback ("# \ \ u ([0-9a-f] {4}) # i ", function ($ matchs) {
return iconv ('UCS-2BE', 'UTF-8', pack ('H4', $ matchs [1] ));
}, $ str);
return $ str;
} else {
return json_encode ($ array, JSON_UNESCAPED_UNICODE);
}
}

Guess you like

Origin www.cnblogs.com/djwhome/p/12750495.html