php中json中文处理函数(中文显示与中文编码)
例子
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy4006')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy4006>function encodeConvert($str,$fromCode,$toCode)
{
if(strtoupper($toCode) == strtoupper($fromCode)) return $str;
if(is_string($str)){
if(function_exists('mb_convert_encoding')){
return mb_convert_encoding($str,$toCode,$fromCode);
}
else{
return iconv($fromCode,$toCode,$str);
}
}
elseif(is_array($str)){
foreach($str as $k=>$v){
$str[$k] = encodeConvert($v,$fromCode,$toCode);
}
return $str;
}
return $str;
}
例子
/**************************************************************
*
* 将数组转换为JSON字符串(兼容中文)
* @param array $array 要转换的数组
* @return string 转换得到的json字符串
* @access public
*
*************************************************************/
function JSON($array) {
arrayRecursive($array, 'urlencode', true);
$json = json_encode($array);
return urldecode($json);
}
/**************************************************************
*
* 使用特定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--;
}
测试例子
$arr = array (
array (
'catid' => '4',
'catname' => '一聚教程网',
'meta_title' => '一聚教程网2'
),
array (
'catid' => '55',
'catname' => 'php教程',
'meta_title' => 'http://www.jquerycn.cn',
)
);
echo JSON($arr);
echo json_encode(encodeConvert($arr,'gb2312','utf-8'));/* */
输出结果如下
[{"catid":"4","catname":"一聚教程网","meta_title":"一聚教程网2"},{"catid":"55","catname":"php教程","meta_title":"http://www.jquerycn.cn"}]
[{"catid":"4","catname":"\u4e00\u805a\u6559\u7a0b\u7f51","meta_title":"\u4e00\u805a\u6559\u7a0b\u7f512"},{"catid":"55","catname":"php\u6559\u7a0b","meta_title":"http:\/\/www.jquerycn.cn"}]
您可能感兴趣的文章:
php5.2 Json中文乱码解决方法
php解析JSON中文乱码问题的解决方法
解决json_encode 函数中文被编码成 null的办法
php的json格式和js跨域调用的代码
php为js数组赋值方法
php响应Json字符串头部出现非法字符“\ufeff”的问题处理
在PHP中处理JSON数组以及对象
php数组转json
php如何将json文本转换成数组
PHP怎么把JSON转换成数组?