Home > php教程 > php手册 > php 解决json

php 解决json

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-06 19:40:24
Original
1340 people have browsed it

用PHP的json_encode来处理中文的时候, 中文都会被编码, 变成不可读的, 类”\u***”的式,如果想汉字不进行转码,这里提供三种方法 1.升级PHP,在PHP5.4, 这个问题终于得以 解决 , Json新增了一个选项: JSON_UNESCAPED_UNICODE, 故名思议, 就是说, Json不要编

用PHP的json_encode来处理中文的时候, 中文都会被编码, 变成不可读的, 类似”\u***”的格式,如果想汉字不进行转码,这里提供三种方法

 

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

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

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

$array = array(
'test'=>urlencode("我是测试")
);
$array = json_encode($array);
echo urldecode($array);
//{"test":"我是测试"} 
Copy after login

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

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

4.例子
$arr = array('name1':"中文",'name2':'abc12');
$jsonstr = decodeUnicode(json_encode($arr));
 
Copy after login

http://www.cnblogs.com/sink_cup/archive/2011/05/28/php_json_encode_unicode_decode.html

http://www.veryhuo.com/a/view/35112.html

http://www.alixixi.com/program/a/2011112776664.shtml

Related labels:
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template