Facebook PHP SDK: How to load page information

A colleague wanted to load all posts of a specific Facebook page, I helped him and this is how I managed to do it.

Facebooks Automated Data Collection Terms do not allow to automatically collect data without their explicit permission, so be sure to have one.

First of all you have to install a few tools. PHP 5.3 and composer are the requirements for this tutorial and you should know how to use them properly.

Then open a terminal and install the requirements using composer:

composer install facebook/php-sdk-v4

Now create a php file in the same folder. The first lines of this file should load all dependecies:

require __DIR__.'/vendor/autoload.php';

You have to register a new app on facebook's developer platform. After registration you get an application id and a app secret. The access token is your id and secret separated by a pipe symbol ('|').

$fb = new Facebook\Facebook([
  'app_id' => 'APPID',
  'app_secret' => 'APP_SECRET',
  'default_graph_version' => 'v2.6',
  'default_access_token' => 'APPID|APP_SECRET',

I wanted to load all posts from 11th December 2012 till 30th June 2013. Facebook uses unix timestamps so I used strtotime to create them:

$since = strtotime('11 December 2012');
$until = strtotime('30 June 2013');

The rest is straightforward:

  • request the data
  • wait for the response
  • iterate over the pages (GraphEdge)

A GraphEdge is a part (a single page) of the result set. In most cases you have to load multiple GraphEdges, which is quite easy, beacuse they are linked and you can get the next one by calling $fb->next($graphEdge).

(You have to replace PAGEID with your page id)

try {
    $request = $fb->request('GET', '/PAGEID/feed?fields=created_time,message,id&until='.$until.'&since='.$since);
    $response = $fb->getClient()->sendRequest($request);
    $graphEdge = $response->getGraphEdge();
    while ($graphEdge) {
        foreach ($graphEdge as $graphNode) {
            $time = $graphNode->getField('created_time')->getTimestamp();
            $id = $graphNode->getField('id');
            $message = $graphNode->getField('message');
        $graphEdge = $fb->next($graphEdge);
} catch (Facebook\Exceptions\FacebookResponseException $e) {
    // When Graph returns an error
    echo 'Graph returned an error: '.$e->getMessage();
} catch (Facebook\Exceptions\FacebookSDKException $e) {
    // When validation fails or other local issues
    echo 'Facebook SDK returned an error: '.$e->getMessage();