json_decode — 对 JSON 格式的字符串进行解码
mixed json_decode ( string $json
[, bool $assoc
= false [, int $depth
= 512 [, int $options
= 0 ]]] )
参数
返回值
Returns the value encoded in json
in appropriate PHP type. Values true, false and null are returned as TRUE
, FALSE
and NULL
respectively. 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