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

Guanhui
Release: 2023-03-02 19:48:01
Original
5457 people have browsed it

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

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!

Related labels:
php
source:php.cn
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