Search code examples
phpcurlflickrjson

Decode json string returned from Flickr API using PHP, curl


Im trying to decode a json string returned from flickr within my PHP code. Im using CURL but it keeps returning a string even when I wrap json_decode() around the json sring variable. Any ideas?

$api_key = '####';
$photoset_id = '###';

$query = 'http://api.flickr.com/services/rest/?&method=flickr.photosets.getPhotos&api_key='.$api_key.'&photoset_id='.$photoset_id.'&extras=url_o,url_t&format=json&jsoncallback=1';

$ch = curl_init(); // open curl session

// set curl options
curl_setopt($ch, CURLOPT_URL, $query);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    
$data = curl_exec($ch); // execute curl session
curl_close($ch); // close curl session
var_dump(json_decode($data));

Solution

  • That's because the returned data is not valid JSON. Its valid JavaScript, though. The returned data is wrapped inside a default callback function called jsonFlickrApi.

    You need to get rid of the JSON callback which wraps the JSON inside a callback function which is then supposed to be executed on the client side. You need to do some string manipulation on the returned JSON to remove the default callback jsonFlickrApi and then pass it to json_decode

    $api_key = '####';
    $photoset_id = '###';
    
    $query = 'http://api.flickr.com/services/rest/?&method=flickr.photosets.getPhotos&api_key='.$api_key.'&photoset_id='.$photoset_id.'&extras=url_o,url_t&format=json';
    
    $ch = curl_init(); // open curl session
    
    // set curl options
    curl_setopt($ch, CURLOPT_URL, $query);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    
    $data = curl_exec($ch); // execute curl session
    curl_close($ch); // close curl session
    
    $data = str_replace( 'jsonFlickrApi(', '', $data );
    $data = substr( $data, 0, strlen( $data ) - 1 ); //strip out last paren
    
    $object = json_decode( $data ); // stdClass object
    
    var_dump( $object );