在 php 中使用 json_encode() 内置函数(php > 5.2)可以使用得 php 中数据可以与其它语言很好的传递并且使用它。
这个函数的功能是将数值转换成json数据存储格式。
1 2 3 4 5 6 7 8 | $arr = array
(
'Name'=>'悟空',
'Age'=>5000
);
$jsonencode = json_encode( $arr );
echo $jsonencode ;
|
Nach dem Login kopieren
程序运行结果如下:
json_encode 函数中中文被编码成 null 了,Google 了一下,很简单,为了与前端紧密结合,Json 只支持utf-8 编码,我认为是前端的 Javascript 也是 utf-8 的原因。
1 2 3 4 5 6 7 | $array = array
(
'title'=>iconv('gb2312','utf-8','这里是中文标题'),
'body'=>'abcd...'
);
echojson_encode( $array );
|
Nach dem Login kopieren
这个程序的运行结果为:
1 | { "title" : "\u8fd9\u91cc\u662f\u4e2d\u6587\u6807\u9898" , "body" : "abcd..." }
|
Nach dem Login kopieren
数组中所有中文在json_encode之后都不见了或者出现\u2353等。
解决方法是用urlencode()函数处理以下,在json_encode之前,把所有数组内所有内容都用urlencode()处理一下,然用json_encode()转换成json字符串,最后再用urldecode()将编码过的中文转回来。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
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 --;
}
function JSON( $array ) {
arrayRecursive( $array , 'urlencode', true);
$json = json_encode( $array );
return urldecode( $json );
}
$array = array
(
'Name'=>'悟空,
'Age'=>5000
);
echo JSON( $array );
|
Nach dem Login kopieren
这次成功了,运行结果如下:
{"Name":"悟空","Age":"5000"}