phpfacebookfacebook-php-sdkfacebook-batch-request

Using Batch request in PHP SDK to get Facebook Album Covers


I am using the PHP SDK through Batch Request (so that its faster to get the covers of all the albums). Its working fine, but the pictures I am getting are not the album covers but the individual pictures in the various cropped sizes.

$albums_resp = $facebook->api('/'.$fbid.'/albums','GET');
$albums = $albums_resp['data'];

//prepare batch query for album covers
$queries = array ();    
foreach ($albums as $album)
{
    if ($album['cover_photo'] != null)
    {
        $query = array('method' => 'GET', 'relative_url' => $album['cover_photo']);
        array_push($queries, $query);
    }
}

$queries_str = json_encode($queries);
$batchResponse = $facebook->api('?batch='.$queries_str, 'POST');

I know that there is another way by using the URL /{albumID}/picture?type=small as indicated here but I still can't get the same image sizes facebook shows in covers (I tried thumbnail, small, cover), and when I use this approach in a batch request for all albums I don't seem to have any way to correlate the response with the album ID. What I get in response is a redirect status 302 with the location of the image.

I don't want to put the image links directly /{albumID}/picture?type=small either because if there are 25 albums it means 25 image redirects, making the page slow.


Solution

  • What I did in the end is use the cover_photo ID to get the full image information (which includes the URLs of the image in different sizes and also the ID itself) and correlated that with the album's cover photo ID.

    $cover_photos = array();
    foreach ($batchResponse as $cover_photo_resp)
    {   
        if ($cover_photo_resp['code'] == 200)
        {
            $cover_photo = json_decode($cover_photo_resp['body'], true);    
            $cover_photos[$cover_photo['id']] = $cover_photo;
        }
    }
    
    //correlate the cover photos with the respective albums, according to the cover photo ID
    for ($i = 0; $i < count($albums); $i++)
    {
        $albums[$i]['cover_photo_obj'] = $cover_photos[$albums[$i]['cover_photo']]; 
    }
    

    What you end up in the end is the $albums[] array of associative arrays each with an extra field in each album referring to the cover_photo_obj object with all the information about the cover photo.