Let JSON understand Chinese better



I believe that when many people use PHP backstage, when AJAX is used for interaction, because the characters are processed by urf-8, so when using json_encode of PHP to process Chinese, Chinese will be coded and become unreadable, similar to “\\\\\\\\\\\u*” The format will also increase the amount of data transmitted to a certain extent.

STR = make JSON understand Chinese better;
echo json_encode($str);
// Output: "8ba9json 66f4 61c2 4e2d 87"

Summarize several solutions.

Method 1: Construct json_encode to support Chinese

The idea is that the string is encrypted by url, and then decrypted by json_encode.

function json_encode_zn($data) {
    // Handling the Chinese Problem of JSON
    if(is_string($data)) {
        $data = urlencode($data);
    }else if(is_array($data)) {
        array_walk_recursive($data, function(&$value) {
            if(is_string($value)) {
                $value = urlencode($value);
    return urldecode(json_encode($data));

STR = make JSON understand Chinese better;
$arr = array ("id"=> 5, "name"=> "Chinese name", "arr"=> array (1, "weapon", "Chinese");
Echo json_encode_zn($str);//"Make JSON understand Chinese better"
Echo json_encode_zn($arr); //{"id": 5, "name", "Chinese name", "arr": [1","weapon","Chinese"]}

Method 2: Use preg_replace to replace u** in Chinese

$code = json_encode($str);
echo preg_replace("#\\u([0-9a-f]+)#ie", "iconv('UCS-2', 'UTF-8', pack('H4', '\1'))", $code);
// Linux uses preg_replace ("\\ u ([0-9a-f]{4})#ie", "iconv ('UCS-2BE','UTF-8', pack ('H4','\ 1'),$code";

Method 3: Direct Processing after Version 5.4

Since json_encode of php5.3 added options parameters and JSON_UNESCAPED_UNICODE was added in version 5.4, the name of JSON is supposed to mean that JSON does not encode unicode.

Echo json_encode ("Chinese", JSON_UNESCAPED_UNICODE); //Chinese