Home  >  Article  >  Backend Development  >  Solution to the problem of Chinese UNICODE transcoding in json_encode in php

Solution to the problem of Chinese UNICODE transcoding in json_encode in php

黄舟
黄舟Original
2017-11-15 15:43:212849browse

我们在之前的文章中给大家介绍了php中json_encode()函数的详解以及使用方法、在我们工作会用到json_encode来处理中文的时候, 中文都会被编码, 变成不可读的, 类似”\u***”的格式,如果想汉字不进行转码,这里提供三种方法解决json_encode中文UNICODE转码的问题!

1.升级PHP,在PHP5.4, 这个问题终于得以解决, Json新增了一个选项: JSON_UNESCAPED_UNICODE, 故名思议, 就是说, Json不要编码Unicode.

<?php
echo json_encode("中文", JSON_UNESCAPED_UNICODE);
//"中文"

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

$array = array(
&#39;test&#39;=>urlencode("我是测试")
);
$array = json_encode($array);
echo urldecode($array);
//{"test":"我是测试"}

3.对unicode码再进行解码,解码函数如下:

function decodeUnicode($str)
{
    return preg_replace_callback(&#39;/\\\\u([0-9a-f]{4})/i&#39;,
        create_function(
            &#39;$matches&#39;,
            &#39;return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");&#39;
        ),
        $str);
}

4.例子

$arr = array(&#39;name1&#39;:"中文",&#39;name2&#39;:&#39;abc12&#39;);
$jsonstr = decodeUnicode(json_encode($arr));

总结:

本文通过三种方法解决了php中json_encode中文UNICODE转码的问题,相信小伙伴在遇到相同的问题可以轻松的解决了!

相关推荐;

php中json_encode的使用示例介绍


php中关于json_encode()函数的详解


Some instructions on the json_encode() and json_decode() functions in php

The above is the detailed content of Solution to the problem of Chinese UNICODE transcoding in json_encode 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