json_decode为字符串变量返回NULL

use*_*494 7 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);
Run Code Online (Sandbox Code Playgroud)

我得到了以下结果:

{"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 
Run Code Online (Sandbox Code Playgroud)

看来我不能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);
Run Code Online (Sandbox Code Playgroud)

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

Ja͢*_*͢ck 4

您的代码看起来不错,所以让我们更进一步研究一下$output到底是什么。它有助于选择可以处理您看不到的 ASCII 范围的表示形式。

echo bin2hex($output);
Run Code Online (Sandbox Code Playgroud)

这将给出一个巨大的字符串,但您最感兴趣的是字符串的正面和背面。

如果这看起来很合理,您可以创建一个中间表示:

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

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

更新

\r根据您基于上述内容的调查,您的字符串似乎在中间某处包含回车符 - - 。

"CA","latitude":"37.42409897","
                            ^
Run Code Online (Sandbox Code Playgroud)

preg_replace()如果无法通过其他方式解决,您可以使用 a 删除它们。

preg_replace("/\r(?!\n)/", '', $output);
Run Code Online (Sandbox Code Playgroud)

这会删除任何\r后面没有\n.