PHP中非UTF-8编码下的JSON处理

PHP自带的json_encode只支持UTF-8编码,其他编码的需要转到UTF-8编码下才能使用。下面是自己写的处理这个问题的函数,分享给大家,希望能对大家有用。注释很详细了,就不说多了,直接看吧。


/*
+------------------------
json_encode 增强版 可将任意编码的变量编码为json字符串
$in 要处理的变量
$charset 编码
+------------------------
**/
function json_encode_set($in,$charset_in='UTF-8',$charset_out='UTF-8')
{

    return iconv('UTF-8',$charset_out,json_encode(iconv_all($charset_in,'UTF-8',$in)));
}

/*
+------------------------
json_decode 增强版
上面json_encode_set的逆运算
$in 要处理的json字符串
$charset 编码
$assoc 返回值 false对象 true数组
+------------------------
**/
function json_decode_set($in,$assoc='true',$charset_in='UTF-8',$charset_out='UTF-8')
{
    return iconv_all('UTF-8',$charset_out,json_decode(iconv($charset_in,'UTF-8',$in),$assoc));
}

/*
+------------------------
iconv 增强版
参数同iconv
原版iconv只能接受字符串
这里的$in可以接受字符串、数组、对象
+------------------------
**/
function iconv_all($in_charset,$out_charset,$in)
{
    if(is_string($in))
    {
        $in=iconv($in_charset,$out_charset,$in);
    }
    elseif(is_array($in))
    {
        foreach($in as $key=>$value)
        {
            $in[$key]=iconv_all($in_charset,$out_charset,$value);
        }
    }
    elseif(is_object($in))
    {
        foreach($in as $key=>$value)
        {
            $in->$key=iconv_all($in_charset,$out_charset,$value);
        }
    }

    return $in;
}

( ! ) Warning: Missing argument 1 for cwppos_show_review(), called in /data/www/enjoyphp/wp-content/themes/flat/content-single.php on line 29 and defined in /data/www/enjoyphp/wp-content/plugins/wp-product-review/includes/legacy.php on line 18
Call Stack
#TimeMemoryFunctionLocation
10.0000355192{main}( ).../index.php:0
20.0001355480require( '/data/www/enjoyphp/wp-blog-header.php' ).../index.php:17
30.163610169736require_once( '/data/www/enjoyphp/wp-includes/template-loader.php' ).../wp-blog-header.php:19
40.164810240880include( '/data/www/enjoyphp/wp-content/themes/flat/single.php' ).../template-loader.php:74
50.246110800064get_template_part( ).../single.php:5
60.246110800584locate_template( ).../general-template.php:167
70.246110800680load_template( ).../template.php:643
80.246210801064require( '/data/www/enjoyphp/wp-content/themes/flat/content-single.php' ).../template.php:686
90.251610786176cwppos_show_review( ).../content-single.php:29

1 评论

  1. 谢谢分享。但我这里后台终端,中文会显示为\u****。

    尝试
    40行后加入
    $in=urlencode($in);

    11行
    return iconv(‘UTF-8′,$charset_out,urldecode(json_encode(iconv_all($charset_in,’UTF-8’,$in))));

    问题暂时解决。

发表评论

电子邮件地址不会被公开。 必填项已用*标注