gpt4 book ai didi

php - json_decode 为字符串变量返回 NULL

转载 作者:可可西里 更新时间:2023-11-01 12:53:30 25 4
gpt4 key购买 nike

我在 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 而在这里正常工作?

最佳答案

您的代码看起来不错,所以让我们更进一步,研究一下 $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 的内容。

关于php - json_decode 为字符串变量返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13947832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com