json_decode为字符串变量返回NULL

时间:2012-12-19 07:57:16

标签: php json

我在json_decode上遇到了一个非常奇怪的问题,使用以下代码:

$url="http://localhost:8983/solr/db/select?wt=json&rows=1&q=94305";
$string=file_get_contents($url);
echo $string; echo '<br><br>';
$json=json_decode($string);
var_dump($json);

我得到了以下结果:

{"responseHeader":{"status":0,"QTime":0,"params":{"q":"94305","wt":"json","rows":"1"}},"response":{"numFound":165,"start":0,"docs":[{"price":"","tags":"ATMs","phone_n":"","location":"37.42409897,-122.1709976 ","store":"Discover ATM","store_id":"478602","state":"CA","latitude":"37.42409897","address":"459 LAGUNITA","zipcode_n":"94305","longitude":"-122.1709976\r","url":"Discover_ATM_459_LAGUNITA_Stanford_CA_94305","city":"Stanford","category":"ATMs","text":["","CA","459 LAGUNITA","94305","Stanford"],"spell":["Discover ATM"]}]}}

NULL 

似乎我不能json_decode这个字符串。但是,当我这样做时(复制上面的字符串的输出并直接将它放到$ string):

$string='{"responseHeader":{"status":0,"QTime":0,"params":{"q":"94305","wt":"json","rows":"1"}},"response":{"numFound":165,"start":0,"docs":[{"price":"","tags":"ATMs","phone_n":"","location":"37.42409897,-122.1709976 ","store":"Discover ATM","store_id":"478602","state":"CA","latitude":"37.42409897","address":"459 LAGUNITA","zipcode_n":"94305","longitude":"-122.1709976\r","url":"Discover_ATM_459_LAGUNITA_Stanford_CA_94305","city":"Stanford","category":"ATMs","text":["","CA","459 LAGUNITA","94305","Stanford"],"spell":["Discover ATM"]}]}}';
$json=json_decode($string);
var_dump($json);

json_decode有效。为什么json_decode在第一部分得到NULL而在这里正常工作?

2 个答案:

答案 0 :(得分:4)

您的代码看起来没问题,所以让我们更进一步,研究$output究竟是什么。选择一个可以处理你看不到的ASCII范围的表示会很有帮助。

echo bin2hex($output);

这会产生一个巨大的字符串,但你会对字符串的正面和背面感兴趣。

如果这看起来像犹太人,你可以创建一个中间表示:

echo preg_replace('@[\x00-\x1f\x7f-\xff]@e', '" (0x" . dechex(ord("\\0")) . ") "', $output);

它用十六进制表示替换较低或较高ASCII范围内的任何字符,从而更容易发现它们:)

<强>更新

根据您的调查,您的字符串似乎包含一个回车符 - \r - 位于中间某处。

"CA","latitude":"37.42409897","
                            ^

如果无法以其他方式解决,则可以删除preg_replace()的那些。

preg_replace("/\r(?!\n)/", '', $output);

删除所有\r后面没有\n

答案 1 :(得分:3)

字符串

中可能有一些NULL字节

使用

删除它
$string = trim($string, "\x0");
$json=json_decode($string);
var_dump($json);

在此页http://localhost:8983/solr/db/select?wt=json&rows=1&q=94305

上将内容类型更改为json
header('Content-type:application/json; charset=utf-8');

删除BOM(字节顺序标记)

if (substr($string, 0,3) == pack("CCC",0xef,0xbb,0xbf)) { 
$string = substr($string, 3); 
}

检查解析json数据时是否发生错误

   $json_errors = array(
         JSON_ERROR_NONE => 'No error has occurred',
         JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
         JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
         JSON_ERROR_SYNTAX => 'Syntax error',
        );
        echo 'Last error : ',

 $json_errors[json_last_error()], PHP_EOL, PHP_EOL;