开发过php代码的程序员都知道,php自带的json_encode函数只能对 utf-8编码数据进行json转换,gbk下中文编码会丢失,变成null值。如何兼容gbk编码,并且utf-8转换后,数据长度会变大,如汉字“你好”会转换为“\u4f60\u597d”,长度有6个变成12。大量文字下,转换后数据会变得更多,占用更多带宽资源。下面通过自定义函数来避免上面两个问题。
function _json_encode($val)
{
if (is_string($val)) return '"'.str_replace(array('\\',"\r","\n",'"','/',"\t","\f"),array('\\\\','\r','\n','\\"','\/','\t','\f'),$val).'"';
if (is_numeric($val)) return $val;
if ($val === null) return 'null';
if ($val === true) return 'true';
if ($val === false) return 'false';
$assoc = false;
$i = 0;
foreach ($val as $k=>$v){
if ($k !== $i++){
$assoc = true;
break;
}
}
$res = array();
foreach ($val as $k=>$v){
$v = _json_encode($v);
if ($assoc){
$k = '"'.addslashes($k).'"';
$v = $k.':'.$v;
}
$res[] = $v;
}
$res = implode(',', $res);
return ($assoc)? '{'.$res.'}' : '['.$res.']';
}
//--通过原生 json_encode及自定义函数来比较下
$arr=array('name'=>'你好','age'=>31);
echo json_encode($arr);//输出{"name":"\u4f60\u597d","age":21},长度为32
echo _json_encode($arr);//输出{"name":"你好","age":21},长度为26
$json_str=_json_encode($arr);
var_dump(json_decode($json_str,true));
echo '<div></div><script>var data='.$json_str.';document.getElementById("messid").innerHTML=data.name;</script>';
未经允许不得转载:任鹏个人博客 » 自定义函数实现php处理gbk编码下json_encode功能
最新评论
Forex wiki. https://lt.forex-stock-bitcoin-brokers.com
Magnificent items from you, man. I have take note your stuff
Following on from the 3rd March Meetings held by economic de
It is remarkable, rather valuable message dfgdlfg2131.32
一般都会有一个沙盒期的,过了沙盒期就会慢慢放出来
百度不收录是应为是新站的原因吗?
The spike in consumer prices that left inflation at a four-d