Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Facebook graph API loop through paging

So I was working with this script to loop through the events from a given page. Suddenly I find it doesn't work anymore :(

I have a feeling it could be a bug, because if you pick any page, view events with an access_token, you can't get any data back for the "next" paginated URL. e.g. try https://graph.facebook.com/evenightclub/events in apigee.com

Any ideas?

($fid is the page object id)

    try {
    $facebook = new Facebook(array(
      'appId'  => '<removed>',
      'secret' => '<removed>',
    ));
    $access_token = $facebook->getAccessToken();

    $events_data = array();
    $offset = 0;
    $limit = 5000;  
    $params = array('access_token' => $access_token);

    //fetch events from Facebook API
    $data = $facebook->api("$fid/events/?limit=$limit&offset=$offset", $params);
    $events_data = array_merge($events_data, $data["data"]);

    //loop through pages to return all results
    while(in_array("paging", $data) && array_key_exists("next", $data["paging"])) {
        $offset += $limit;
        $data = $facebook->api("$fid/events/?limit=$limit&offset=$offset", $params);
        $events_data = array_merge($events_data, $data["data"]);
    }}
like image 340
Nathan Waters Avatar asked Mar 06 '12 00:03

Nathan Waters


1 Answers

Your code works for me, the only thing that I did is to make sure that count($data["data"]) > 0 before merging it with the existing information. So it looks like this:

//loop through pages to return all results
while(in_array("paging", $data) && array_key_exists("next", $data["paging"])) {
    $offset += $limit;
    $data = $facebook->api("$fid/events/?limit=$limit&offset=$offset", $params);
    // make sure we do not merge with an empty array
    if (count($data["data"]) > 0){
        $events_data = array_merge($events_data, $data["data"]);
    } else {
        // if the data entry is empty, we have reached the end, exit the while loop
        break;
    }
}}
like image 85
Ioana Avatar answered Oct 23 '22 09:10

Ioana