Search code examples
phpfacebookapifacebook-graph-apifacebook-php-sdk

Facebook API (PHP) : Get Full Ads List


I am using Facebook API to fetch the full Ads list.

The Code is working, But it return only 25 Ad in case of i have 150+ Ad in my account.

I guess that happens because of the query limits on the Facebook API.

My Code:

$account = new AdAccount('act_<AD_ACCOUNT_ID>');
$account->read();

$fields_adset = array(
  AdSetFields::ID,
  AdSetFields::NAME,
  AdSetFields::CAMPAIGN_ID,
  AdSetFields::STATUS,
);

$ads = $account->getAds($fields_adset);

foreach ($ads as $adset) {
    $adset_id = $adset->{AdSetFields::ID};
    echo  $adset_id;
    //print_r($adset);
    //exit();
}

So, they mentioned in the documentation that :

Use Asynchronous Requests to query a huge amount of data

Reference (1) : https://developers.facebook.com/docs/marketing-api/best-practices/

Reference (2) : https://developers.facebook.com/docs/marketing-api/insights/best-practices/#asynchronous

But, I can't apply that "Asynchronous" requests to my code to fetch the Full Ad List,

Please help me to fetch the full Ads list

Thank you.


Solution

  • You should implement pagination (or request a limit more high). With the PHP SDK you can implement the cursor as described in the doc here or more simply set the Implicit Fetching, as example:

    ..
    use FacebookAds\Cursor;
    
    ...
    Cursor::setDefaultUseImplicitFetch(true);
    
    
    $account = new AdAccount('act_<AD_ACCOUNT_ID>');
    $account->read();
    
    $fields_adset = array(
      AdSetFields::ID,
      AdSetFields::NAME,
      AdSetFields::CAMPAIGN_ID,
      AdSetFields::STATUS,
    );
    
    $ads = $account->getAds($fields_adset);
    
    foreach ($ads as $adset) {
        $adset_id = $adset->{AdSetFields::ID};
        echo  $adset_id;
        //print_r($adset);
        //exit();
    }
    

    Hope this help