PHP 一个正确的json字符串 执行json_decode返回null解析失败原因
在PHP5.4之前 json_decode函数有两个参数json_decode有两个参数,第一个是待解析的字符串,第二个是是否解析为Array
json_decode/josn_encode要求的字符串比较严格:
(1)使用UTF-8编码
$output = iconv('gbk', 'utf8', $output); $array = array('title'=>iconv('gb2312','utf-8','这里是中文标题'),'body'=>'abcd...');
(2)不能在最后元素有逗号
preg_replace('/,\s*([\]}])/m', '$1', $output)
(3)不能使用单引号
$output = str_replace("'", '"', $output);
(4)不能有\r,\t,如果有请替换
//$ret=preg_replace("/\t/", " ", $ret); //$jsonstr = preg_replace("/\n/", ' ', $jsonstr); $jsonstr = str_replace("\n", ' ', $jsonstr);
(5)不小心在返回的json字符串中返回了BOM头的不可见字符 -- tirm去除bom头 或者其他控制字符
$result = trim($result, "\xEF\xBB\xBF"); //去除bom头
preg_replace( '/[\x00-\x1F]/','',$str);//去除控制符
浙公网安备 33010602011771号