PHP-json使用注意点

来源:互联网 发布:eagle软件下载 编辑:程序博客网 时间:2024/05/18 01:09

json_decode — 对 JSON 格式的字符串进行解码

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

参数

json

待解码的 json string 格式的字符串。

这个函数仅能处理 UTF-8 编码的数据。

Note:

PHP implements a superset of JSON as specified in the original » RFC 7159.

assoc

当该参数为 TRUE 时,将返回 array 而非 object 。

depth

指定递归深度。

options

JSON解码的掩码选项。 现在有两个支持的选项。 第一个是JSON_BIGINT_AS_STRING, 用于将大整数转为字符串而非默认的float类型。第二个是 JSON_OBJECT_AS_ARRAY, 与将assoc设置为 TRUE 有相同的效果。

返回值

Returns the value encoded in json in appropriate PHP type. Values truefalse and null are returned as TRUEFALSE and NULLrespectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.



json_decode要求的字符串比较严格:

(1)使用UTF-8编码
(2)不能在最后元素有逗号
(3)不能使用单引号
(4)不能有\r,\t,如果有请替换


编码 转化


public static function changeStringEncoding($string){
$finalEncoding = 'UTF-8';
if( strlen($string) <= 0 ){
return '';
}
$encode = mb_detect_encoding($string, array('GB2312','GBK','UTF-8'));
if($encode == 'GB2312'){
$string = iconv( 'GBK', $finalEncoding , $string);
}else if($encode == 'GBK') {
$string = iconv( 'GBK' , $finalEncoding , $string);
} else if($encode == 'EUC-CN'){
$string = iconv( 'GBK' , $finalEncoding , $string);
} else {
$string = iconv( 'GB2312' , $finalEncoding ,$string);
}
return $string;

}


 或 使用前确保是 UTF-8

$contents file_get_contents($url); 
$contents utf8_encode($contents); 
$results json_decode($contents); 


友情链接

http://blog.sina.com.cn/s/blog_7253e3930102wdbd.html

http://php.net/manual/zh/function.json-decode.php

原创粉丝点击