Home >Backend Development >PHP Tutorial >Solve json_encode Chinese transcoding problem

Solve json_encode Chinese transcoding problem

angryTom
angryTomforward
2020-01-17 17:42:362832browse

Solve json_encode Chinese transcoding problem

When doing interface development, it is often used to return json data. There is a function json_encode in php to convert the array into json data format, but have you ever encountered if the array contains In Chinese, the returned data is empty. Two solutions are written below

The first way

Chinese urlencode, this way if there are multi-digit arrays Sorry

function encode_json($str) {  
    return urldecode(json_encode(url_encode($str)));      
}  
function url_encode($str) {  
    if(is_array($str)) {  
        foreach($str as $key=>$value) {  
            $str[urlencode($key)] = url_encode($value);  
        }  
    } else {  
        $str = urlencode($str);  
    }  
      
    return $str;  
}

The second way

Add the JSON_UNESCAPED_UNICODE parameter. Note that it must be php5.4 or later to use it

json_encode($arr,JSON_UNESCAPED_UNICODE);

I use Usually there will be multiple parameters

$data_string=json_encode($para,JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);

Writing this article to remind myself of this problem

This article comes from the php Chinese website, php tutorial column, welcome to learn!

The above is the detailed content of Solve json_encode Chinese transcoding problem. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:www.phpsong.com. If there is any infringement, please contact admin@php.cn delete