Getting a list of page albums using Facebook PHP SDK v5

So, like the title says, I wanted to get a list of the albums, from the Facebook page of BarenDK so I could at some point get the id’s of the pictures in those albums and create a nice picture-viewer on BarenDK’s Website. Easy, right?

Just Google what you want to do, and follow the examples in the docs. Yeah Right.

Even the suggested solution on StackOverflow doesn’t “really” solve the problem, because it’s just a verbatim copy of the docs, and it doesn’t work!

So after spending one hour on what should come off as a total no-brainer, I finally solved it with this.

<?php 

define('FACEBOOK_SDK_V4_SRC_DIR',
	__DIR__ . '/lib/php-graph-sdk-5.0.0/src/Facebook/');

require_once(__DIR__ . '/lib/php-graph-sdk-5.0.0/src/Facebook/autoload.php');


$fb = new Facebook\Facebook([
  'app_id' => '{app-id}',
  'app_secret' => '{app-secret}',
  'default_graph_version' => 'v2.3',
  // . . .
  ]);
  
// Send the request to Graph
try {
	$response = $fb->get('/{group-id}/albums', 
		"{app-token}");
} catch(Facebook\Exceptions\FacebookResponseException $e) {
  // When Graph returns an error
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  // When validation fails or other local issues
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

$graphNode = $response->getGraphEdge();

print_r($graphNode);

You need to replace some things in the code, and bear a couple of things in mind.

  1. '{app-id}' is changed to your App-id, you get it from the app dashboard.
  2. '{app-secret}' is changed to your App-secret, also app dashboard.
  3. '{app-token}' can be made by combining the app-id and app-secret with a bar; like '{app-id}|{app-secret}'.
  4. '{group-id}' is changed to the id of the group, whose albums you want.

Lastly, all of this, is in a file.php, and in the same directory as the file, I have a lib folder, inside it is the php-graph-sdk-5.0.0 folder, and inside this is, src/Facebook/… I’ve included this as well, since the require’s and pathing might not be that obvious either.

If you have any issues, you can try commenting below, but really I’ll recommend you bump a bit around on Google and see what you find. They’ve probably changed the API again after I’ve written this!

I don’t need an App-token to do this? What is this??

Well, you can do it without, and receive the lovely,
Graph returned an error: (#4) Application request limit reached-error.

See the question on StackOverflow How do I get the App Access Token via the Facebook PHP SDK? for more about this.

And now, everything works!

I hope this helps somebody. I know I usually get a lot out of working examples.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.