skip to Main Content

I am grabbing all of the campaigns associated with a user and trying to get insights for the campaigns. I get the campaigns just fine but when I try to get the insights it always returns null. I have tried changing the days and different fields.

$api = Api::instance();

$id = trim($_POST['actid']);

$account = new AdAccount($id);

$fields = array(
    CampaignFields::NAME,
    CampaignFields::ID,
);

$campaigns = $account->getCampaigns($fields);



$cleanArray = [];
foreach ($campaigns as $campaign) {

    $campFields = array(
    AdsInsightsFields::CPC,
);

$params = array(
    'time_range' => array(
    'since' => (new DateTime("-1 day"))->format('Y-m-d'),
    'until' => (new DateTime('NOW'))->format('Y-m-d'),
    ),
);

$campInsights = $campSelect->getInsights($campFields, $params);
$innerArray = [];
array_push($innerArray,$campaign->{CampaignFields::NAME});
array_push($innerArray,$campaign->{CampaignFields::ID});
array_push($innerArray,$campInsights->{AdsInsightsFields::CPC});
array_push($cleanArray,$innerArray);
}

header('Content-Type: application/json');
echo json_encode($cleanArray);

2

Answers


  1. Chosen as BEST ANSWER

    So it was a scope issue as I still needed to iterate through the object as an array. Posting this to help others.

    foreach($campInsights as $insights){
        $cpc = $insights->{AdsInsightsFields::CPC}.PHP_EOL;
        $clicks = $insights->{AdsInsightsFields::WEBSITE_CLICKS}.PHP_EOL;
    }
    

    After I looped through the object, I was able to grab the values.


  2. The call to getInsights returns an iterator, as requests to gather insights can return a set of results.

    If you’re sure it will only return a single result, you can just access $campInsights[0].

    You also have an error in your code in this line, as $campSelect is not defined:

    $campInsights = $campSelect->getInsights($campFields, $params);
    

    It should be:

    $campInsights = $campSelect->getInsights($campFields, $params);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search