PHP JSON显示中文 和数字

本文介绍了解决JSON字符串中缺少双引号的问题,并演示了如何处理包含中文字符的JSON字符串,确保其正确编码与解码。

如果json字符串的key缺少双引括起来,则json_decode会失败,判断是否存在缺少双引括起来的key,如缺少则先用正则替换为"key",再进行json_decode操作

<?php
/** 兼容key没有双引括起来的JSON字符串解析
 * @param String $str JSON字符串
 * @param boolean $mod true:Array,false:Object
 * @return Array/Object
 */
function json_replace_key($str) 
{	
	$str = trim( $str );
	$str = ltrim( $str, '(' );
	$str = rtrim( $str, ')' );
	$a = preg_split('#(?<!\\\\)\"#', $str );
	for( $i=0; $i < count( $a ); $i+=2 )
	{
		$s = $a[$i];
		$s = preg_replace('#([^\s\{\}\:\,]+):#', '"\1":', $s );
		$a[$i] = $s;
	}
	return implode( '"', $a );
}

function ext_json_decode($str, $mode = false)
{
    $str = json_replace_key($str); 
    //json中的Key增加上引号.
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new EncryptException('Could not encrypt the data.');
    }
    return json_decode($str, $mode);
}

$str1 = '{name:"fdip:zone"}';
var_dump(ext_json_decode($str1, true)); // array(1) { ["name"]=> string(8) "fdip:zone" }
?>

 Json只支持 utf-8 编码,所有用header

<?php
/**************************************************************
 *
 * 使用特定function对数组中所有元素做处理
 * @param    string    &$array        要处理的字符串
 * @param    string    $function    要执行的函数
 * @return boolean    $apply_to_keys_also        是否也应用到key上
 * @access public
 *
 *************************************************************/
function arrayRecursive(&$array, $function, $apply_to_keys_also = false) {
    static $recursive_counter = 0;
    if (++$recursive_counter > 1000) {
        die('possible deep recursion attack');
    }
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            arrayRecursive($array[$key], $function, $apply_to_keys_also);
        } else {
            $array[$key] = $function($value);
        }

        if ($apply_to_keys_also && is_string($key)) {
            $new_key = $function($key);
            if ($new_key != $key) {
                $array[$new_key] = $array[$key];
                unset($array[$key]);
            }
        }
    }
    $recursive_counter--;
}

/**************************************************************
 *
 * 将数组转换为JSON字符串(兼容中文)
 * @param    array    $array        要转换的数组
 * @return string        转换得到的json字符串
 * @access public
 *
 *************************************************************/
function JSON($array) {
    arrayRecursive($array, 'urlencode', true);
    $json = json_encode($array);
    return urldecode($json);
}
$array = array(
    'Name' => '希亚',
    'Age' => 20
);
header("Cache-Control: no-cache, no-store, must-revalidate, max-age=-1");
header("Content-Type: application/json; charset=utf-8");
echo JSON($array);
echo "<br/>";
print_r(json_decode(JSON($array)));

echo "<br/>------default------<br/>";
$tt = json_encode($array);
print_r($tt);
echo "<br/>";
exit(json_decode($tt));
?>

{"Name":"希亚","Age":"20"}
stdClass Object ( [Name] => 希亚 [Age] => 20 )
------default------
{"Name":"\u5e0c\u4e9a","Age":20}
stdClass Object ( [Name] => 希亚 [Age] => 20 )

打印json_decode结果  json_decode加了true参数会返回关联数组,否则出现stdClass Object对象

对于PHP5.4+版本,json_decode函数第二个参数,可以用来限制转义范围。

要限制中文,使用JSON_UNESCAPED_UNICODE参数。

json_encode($result, JSON_UNESCAPED_UNICODE);

某些数字类型不转化字符串,不能用JSON_NUMERIC_CHECK

json_encode([ 'vcc_id' => (int) "1213", 'user_id' =>"1213" ]); 
$s = '[{\\&quot;table\\&quot;:\\&quot;a\\&quot;,\\&quot;field\\&quot;:\\&quot;value\\&quot;,\\&quot;max\\&quot;:60,\\&quot;min\\&quot;:null}]';
 
$s = html_entity_decode($s);
$s = stripslashes($s);
 
print_r(json_decode($s, 1));
$areaInfo = json_decode($areaInfo, true);
if (JSON_ERROR_NONE === json_last_error()) {

json_last_error错误msg对照表:
    0 = JSON_ERROR_NONE
    1 = JSON_ERROR_DEPTH
    2 = JSON_ERROR_STATE_MISMATCH
    3 = JSON_ERROR_CTRL_CHAR
    4 = JSON_ERROR_SYNTAX
    5 = JSON_ERROR_UTF8

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值