Search code examples
phpapiflickrjson

Print Flickr variables from API using json_decode


I want to create a flickr photo url by calling variables from my json_decoded api request, but I can't get it to output any values...

Here's the code:

    $flickr = file_get_contents("http://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key=b5c6ad8347e6dbeb62743d1be36dc9e1&photoset_id=72157628996146229&format=json&nojsoncallback=1", TRUE);
    $flickr = json_decode($flickr, TRUE);
    var_dump($flickr);

echo $flickr[photoset][photo][id];

Sadly this is outputting nothing...

Any ideas?

Simple ones :)

Many thanks.


Solution

  • Accessing array elements

    echo $flickr[photoset][photo][id];
    

    Should be:

    echo $flickr['photoset']['photo']['id'];
    

    In PHP strings DOCs must be surrounded by either single (') or double quotes (") when used as array element keys. If they are not then PHP will attempt to evaluate them as constants DOCs.

    Looping over the dataset

    In this case json_decode() DOCs is returning an array of data so you will need to loop over it to access it:

    foreach ($flickr['photoset']['photo'] as $item) {
        echo $item['id'];
    }
    

    For more information on PHPs foreach see the manual.