Home  >  Article  >  php教程  >  php中GBK/GB2312页面使用json_decode()中文丢失

php中GBK/GB2312页面使用json_decode()中文丢失

WBOY
WBOYOriginal
2016-05-25 16:44:571474browse

用json_decode()将数组/对象序列化为JSON字符串的时候基本上只支持 UTF-8/ASCII编码,而我们有的站采用了GBK/GB2312编码,这个时候,直接使用json_encode/json_decode的时候就可能会出问题了,代码如下:

<?php
$json = &#39;{"a":"中国人人"}&#39;;
var_dump(json_decode($json));
?>
//结果 
//{"text":null,"status":1}

比如转含有中文的字符字变成空(null),但有时候我们又必须得用gb编码而又要用到json_decode()转换的时候呢?什么办呢?自己昨晚写了一个不用数据库的一个添加音乐的小后台,也就是用php添加音乐,然后生成xml菜单,不用数据库那也得用一个方式来保存数据了,保存成文本的数据再可以直接拿出来用的,我想是把数组json_decode()用它转成json格式,用的时候再拿出来用它json_encode转回数组就可以了(可能最近弄js被json影响了,好像把数组序列化还有更好的方法,比如用:serialize()和unserialize()),呵呵,转正题,既然json_decode()在gb编码上转不了中文,那么我们可以先把中文转成英文编码的形式,那可以使用这个urlencode()转一下编码,再做json_decode()转换,使用的时候,再用urldecode()转成中文就可以了,代码如下:

<?php
/*
	字符串GBK转码为UTF-8,数字转换为数字。 
*/
function ct2($s) {
    if (is_numeric($s)) {
        return intval($s);
    } else {
        return iconv("GBK", "UTF-8", $s);
    }
}
/*
	批量处理gbk->utf-8 
*/
function icon_to_utf8($s) {
    if (is_array($s)) {
        foreach ($s as $key => $val) {
            $s[$key] = icon_to_utf8($val);
        }
    } else {
        $s = ct2($s);
    }
    return $s;
}
echo json_encode(icon_to_utf8("厦门"));
?>

               
               

本文地址:

转载随意,但请附上文章地址:-)

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