php json_decode 返回值为null
使用file_get_contents,curl获取的内容含有BOM
得到的数据前面有三个看不到的字符(无BOM 也是没用的),
所以只要将得到的字符串,substr($str,3)就行了
json_decode函数能够接收utf8编码的参数,但是当参数中包含BOM时,json_decode就会失效。
这个函数能将给定的字符串转换成UTF-8编码,移除其中的BOM。
下面是PHP代码:
function prepareJSON($input) {
//This will convert ASCII/ISO-8859-1 to UTF-8.
//Be careful with the third parameter (encoding detect list), because
//if set wrong, some input encodings will get garbled (including UTF-8!)
$imput = mb_convert_encoding($input, 'UTF-8', 'ASCII,UTF-8,ISO-8859-1');
//Remove UTF-8 BOM if present, json_decode() does not like it.
if(substr($input, 0, 3) == pack("CCC", 0xEF, 0xBB, 0xBF)) $input = substr($input, 3);
return $input;
}
//Usage:
$myFile = file_get_contents('somefile.json');
$myDataArr = json_decode(prepareJSON($myFile), true);
以下几个方面也需要注意。
一、只能使用双引号(")
在JSON里只用"来表示字符串,例如
- {'aa':'sdf'}
- 'adf'
- ['1', '2']
这些使用'的统统不能解析,而且对象的属性也必须用",也就是只能用双引号..
直接用str_replace("'", '"', $json) 来替换就好了,,不过就是会把所有单引号转换为双引号
二、不能有多余的逗号(,)
例如,
- [1,2,]
- {"a":1,"b":2,}
这个我记得ie6里也是不支持的,会出错。
用正则替换掉,preg_replace('/,\s*([\]}])/m', '$1', $json)
三、不支持一些转义
字符的表示方式方式有很多种,但下面的都不支持
- \x26
因为php也支持这种十六进制方式,所以可以用eval来达到转义效果。
如果是中文的注意,要用utf-8
json标准http://www.ietf.org/rfc/rfc4627.txt?number=4627
浙公网安备 33010602011771号