Home  >  Article  >  Backend Development  >  What should I do if php escapes Chinese characters?

What should I do if php escapes Chinese characters?

藏色散人
藏色散人Original
2021-03-19 09:43:182565browse

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);

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

echo json_encode($arr,JSON_UNESCAPED_UNICODE);

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

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

 

【推荐: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!

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
Previous article:How to install php5-fpmNext article:How to install php5-fpm