arrays – JSON Decode issue with PHP (Pixabay API)-ThrowExceptions

Exception or error:

I’m trying to get the image URL of the first object from the Pixabay API in PHP. Unfortunately with my attempt I get

$encodedjson->hits[0]->largeImageURL

an empty string back.

{
"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,
        ...
    },
    ...
]
}
How to solve:

Problem here is bad json. Extra comma on the end makes the problem. Thats why you should use something like https://jsonlint.com/ to test JSON.

Before this I tried in localhost to get json data from api.
After json_decode function I got NULL value.

And after deleting extra commas on the end I get following response from 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) } } }

Full code:

<?php

$test = file_get_contents('http://www.mocky.io/v2/5e6fc5d233000086caf07c02');

$data = json_decode($test);

echo $data->hits[0]->largeImageURL;

?>

And testing your example

https://pixabay.com/get/ed6a99fd0a76647_1280.jpg

Leave a Reply

Your email address will not be published. Required fields are marked *