php json_encode 中文乱码
http://www.nowamagic.net/php/php_FunctionJsonEncode.php数组中所有中文在json_encode之后都不见了或者出现\u2353等。
解决方法是用urlencode()函数处理以下,在json_encode之前,把所有数组内所有内容都用urlencode()处理一下,然用json_encode()转换成json字符串,最后再用urldecode()将编码过的中文转回来。
<?php
/**************************************************************
*
*使用特定function对数组中所有元素做处理
*@paramstring&$array要处理的字符串
*@paramstring$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字符串(兼容中文)
*@paramarray$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
);
echo JSON($array);
?>
页:
[1]