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

Solve json_encode Chinese transcoding problem

angryTom
Release: 2023-04-08 08:52:02
forward
2834 people have browsed it

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;  
}
Copy after login

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);
Copy after login

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);
Copy after login

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!

Related labels:
source:www.phpsong.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template