这两天自己做了个公共API接口,遇到了一个很烦人的bug,就是接口传回了json字符串,但是本地的后台在获取字符串后,用json_decode()转码的话返回NULL。
在网上找了很多办法,最后终于用trim($result,chr(239).chr(187).chr(191))这个函数搞定了!
原因就是UTF-8的DOM头影响,用trim($result,chr(239).chr(187).chr(191))切割掉字符串前面的BOM头就可以正常转码了。
代码:
$result = getAPIData($url);
$result = trim($result,chr(239).chr(187).chr(191));
$result = json_decode($result,true);
附:
BOM头的另一种解决方案:
$result = getAPIData($url);
$result = substr($result,3);
$result = json_decode($result,true);
这种方案按说也可以,而且效率更高。但是我用了之后并不起作用,不知道为什么……
附:
json_decode()返回为NULL的其他原因与解决方案。
0:
5.3版本以上的PHP自带一个json_last_error()函数,可以返回最近一次的json编码错误代码。
1:编码格式问题:
json字符串的编码格式必须是utf-8格式的。
这里有两种查看字符串编码格式的方法:
①:在浏览器中按F12,找到
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
标签,charset后面就是编码格式。 ②:使用
$encode = mb_detect_encoding($result, array("ASCII","UTF-8","GB2312","GBK","BIG5"));
函数,返回值就是字符串的编码格式。 如果确定是编码格式问题的话,就用iconv()函数来转码。
$result = getAPIData($url);
$result = iconv('gbk', 'utf8', $result);
$result = json_decode($result,true);
2:json语法错误
如果感觉是语法错误的话最好百度一个工具来测试一下到底是哪里的语法错误。
用法很简单,把json字符串复制进去之后按“校验”按钮即可。
①:json字符串两遍必须以双引号来包含。
//演示:被单引号包含的字符串修改为被双引号修改的字符串
$result = getAPIData($url);
$result = str_replace("'", '"', $result);
$result = json_decode($result,true);
②:json对象中最后一个元素后面不能有逗号。
$result = getAPIData($url);
$result = preg_replace('/,s*([]}])/m', '$1', $output);
$result = json_decode($result,true);