我试图从PHP中的Pixabay获取第一个对象的图像URL。不幸的是我的尝试
$encodedjson->hits[0]->largeImageURL一根空的绳子。
{
"total": 4692,
"totalHits": 500,
"hits": [
{
"id": 195893,
"pageURL": "https://pixabay.com/en/blossom-bloom-flower-195893/",
"largeImageURL": "https://pixabay.com/get/ed6a99fd0a76647_1280.jpg",
"userImageURL": "https://cdn.pixabay.com/user/2013/11/05/02-10-23-764_250x250.jpg",
},
{
"id": 73424,
...
},
...
]
}发布于 2020-03-16 18:38:29
这里的问题是坏json。最后加上逗号会引起问题。这就是为什么您应该使用类似于https://jsonlint.com/的东西来测试JSON。
在此之前,我尝试在localhost中从api中获取json数据。在json_decode函数之后,我得到了空值。
在最后删除额外的逗号后,我得到来自json_decode()的响应
object(stdClass)#1 (3) { ["total"]=> int(4692) ["totalHits"]=> int(500) ["hits"]=> array(2) { [0]=> object(stdClass)#2 (4) { ["id"]=> int(195893) ["pageURL"]=> string(51) "https://pixabay.com/en/blossom-bloom-flower-195893/" ["largeImageURL"]=> string(48) "https://pixabay.com/get/ed6a99fd0a76647_1280.jpg" ["userImageURL"]=> string(64) "https://cdn.pixabay.com/user/2013/11/05/02-10-23-764_250x250.jpg" } [1]=> object(stdClass)#3 (1) { ["id"]=> int(73424) } } }
完整代码:
<?php
$test = file_get_contents('http://www.mocky.io/v2/5e6fc5d233000086caf07c02');
$data = json_decode($test);
echo $data->hits[0]->largeImageURL;
?>并测试您的示例
https://pixabay.com/get/ed6a99fd0a76647_1280.jpg
https://stackoverflow.com/questions/60711197
复制相似问题