【问题标题】:JSON Decode issue with PHP (Pixabay API)PHP 的 JSON 解码问题(Pixabay API)
【发布时间】:2020-03-16 18:14:20
【问题描述】:

我正在尝试从 PHP 中的 Pixabay API 中获取第一个对象的图像 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,
        ...
    },
    ...
]
}

【问题讨论】:

标签: php arrays json api


【解决方案1】:

这里的问题是错误的 json。末尾的额外逗号会导致问题。这就是为什么你应该使用类似https://jsonlint.com/ 的东西来测试 JSON。

在此之前,我尝试在 localhost 中从 api 获取 json 数据。 在 json_decode 函数之后,我得到了 NULL 值。

在最后删除多余的逗号后,我得到了来自 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-05
    • 2012-10-20
    • 1970-01-01
    • 2013-05-01
    • 2012-03-22
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多