Home >Backend Development >PHP Problem >How to solve the Chinese garbled characters of json_decode function in PHP?

How to solve the Chinese garbled characters of json_decode function in PHP?

Guanhui
GuanhuiOriginal
2020-07-21 16:00:175516browse

How to solve the Chinese garbled characters of json_decode function in PHP?

How to solve the Chinese garbled characters of json_decode function in PHP?

Solution to the Chinese garbled code of the json_decode function in PHP: 1. Use the function "urldecode()" to decode the data, and then perform JSON decoding after decoding. The function of its function is to decode the encoded URL string; 2. , When encoding JSON, just do not encode Chinese.

Sample code

<?php
    $testJSON=array(&#39;name&#39;=>&#39;中文字符串&#39;,&#39;value&#39;=>&#39;test&#39;);
    echo json_encode($testJSON);
?>

查看输出结果为:
{“name”:”\u4e2d\u6587\u5b57\u7b26\u4e32″,”value”:”test”}
可见即使用UTF8编码的字符,使用json_encode也出现了中文乱码。解决办法是在使用json_encode之前把字符用函数urlencode()处理一下,然后再json_encode,输出结果的时候在用函数urldecode()转回来。具体如下:


<?php
    $testJSON=array(&#39;name&#39;=>&#39;中文字符串&#39;,&#39;value&#39;=>&#39;test&#39;);
    //echo json_encode($testJSON);
    foreach ( $testJSON as $key => $value ) {
        $testJSON[$key] = urlencode ( $value );
    }
    echo urldecode ( json_encode ( $testJSON ) );
?>


查看输出结果为:



{“name”:”中文字符串”,”value”:”test”}

Recommended tutorial: "PHP"

The above is the detailed content of How to solve the Chinese garbled characters of json_decode function in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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