What should I do if php escapes Chinese characters?

藏色散人
Release: 2023-03-08 20:36:01
Original
2511 people have browsed it

php转义汉字的解决办法:1、使用自定义的“function json_encode_ex($value)”方法实现中文不转义;2、通过“JSON_UNESCAPED_UNICODE”选项实现不转义;3、使用urldecode来解码。

What should I do if php escapes Chinese characters?

本文操作环境:windows7系统、PHP7.1版,DELL G3电脑

php实现json_encode()中文字符不转义

在项目中,php提供的接口使用json_encode()函数,在处理中文的时候, 中文都会被编码成Unicode码, 变成不可读的, 类似”\u***”的格式,如果想汉字不进行转码,这里提供三种方法

1.php版本在5.3及以下自己写函数实现中文不转义

function json_encode_ex($value)
{
    if(version_compare(PHP_VERSION,&#39;5.4.0&#39;,&#39;<&#39;)){
        $str = json_encode($value);
        $str = preg_replace_callback(
                                    "#\\\u([0-9a-f]{4})#i",
                                    function($matchs)
                                    {
                                         return iconv(&#39;UCS-2BE&#39;, &#39;UTF-8&#39;, pack(&#39;H4&#39;, $matchs[1]));
                                    },
                                     $str
                                    );
        return $str;
    }else{
        return json_encode($value, JSON_UNESCAPED_UNICODE);
    }
}
echo json_encode_ex($arr);
Copy after login

2.php版本5.4以上,json_encode()新增了一个选项,JSON_UNESCAPED_UNICODE 意思是json不要unicode编码

echo json_encode($arr,JSON_UNESCAPED_UNICODE);
Copy after login

3.先把中文汉字进行urlencode然后再使用json_encode,json_encode之后再次使用urldecode来解码,这样编码出来的json数组中的汉字就不会出现unicode编码了

$arr = array(
    &#39;key&#39;=>urlencode("测试")
);
$json = json_encode($arr);
echo urldecode($json);
//{"key":"测试"}
Copy after login

 

【推荐:PHP视频教程

The above is the detailed content of What should I do if php escapes Chinese characters?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!