Reporting Samples

The code samples below provide examples of common reporting functions using the AdWords API. Client Library.

Download a criteria performance report with selector

New

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201705\Reporting;

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

use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\Reporting\v201705\DownloadFormat;
use Google\AdsApi\AdWords\Reporting\v201705\ReportDefinition;
use Google\AdsApi\AdWords\Reporting\v201705\ReportDefinitionDateRangeType;
use Google\AdsApi\AdWords\Reporting\v201705\ReportDownloader;
use Google\AdsApi\AdWords\ReportSettingsBuilder;
use Google\AdsApi\AdWords\v201705\cm\Predicate;
use Google\AdsApi\AdWords\v201705\cm\PredicateOperator;
use Google\AdsApi\AdWords\v201705\cm\ReportDefinitionReportType;
use Google\AdsApi\AdWords\v201705\cm\Selector;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * Downloads CRITERIA_PERFORMANCE_REPORT for the specified client customer ID.
 */
class DownloadCriteriaReportWithSelector {

  public static function runExample(AdWordsSession $session, $filePath) {
    // Create selector.
    $selector = new Selector();
    $selector->setFields(['CampaignId', 'AdGroupId', 'Id', 'Criteria',
        'CriteriaType', 'Impressions', 'Clicks', 'Cost']);

    // Use a predicate to filter out paused criteria (this is optional).
    $selector->setPredicates([
        new Predicate('Status', PredicateOperator::NOT_IN, ['PAUSED'])]);

    // Create report definition.
    $reportDefinition = new ReportDefinition();
    $reportDefinition->setSelector($selector);
    $reportDefinition->setReportName(
        'Criteria performance report #' . uniqid());
    $reportDefinition->setDateRangeType(
        ReportDefinitionDateRangeType::LAST_7_DAYS);
    $reportDefinition->setReportType(
        ReportDefinitionReportType::CRITERIA_PERFORMANCE_REPORT);
    $reportDefinition->setDownloadFormat(DownloadFormat::CSV);

    // Download report.
    $reportDownloader = new ReportDownloader($session);
    $reportDownloadResult =
        $reportDownloader->downloadReport($reportDefinition);
    $reportDownloadResult->saveToFile($filePath);
    printf("Report with name '%s' was downloaded to '%s'.\n",
        $reportDefinition->getReportName(), $filePath);
  }

  public static function main() {
    // Generate a refreshable OAuth2 credential for authentication.
    $oAuth2Credential = (new OAuth2TokenBuilder())
        ->fromFile()
        ->build();

    // See: ReportSettingsBuilder for more options (e.g., suppress headers)
    // or set them in your adsapi_php.ini file.
    $reportSettings = (new ReportSettingsBuilder())
        ->fromFile()
        ->includeZeroImpressions(false)
        ->build();

    // See: AdWordsSessionBuilder for setting a client customer ID that is
    // different from that specified in your adsapi_php.ini file.
    // Construct an API session configured from a properties file and the OAuth2
    // credentials above.
    $session = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->withReportSettings($reportSettings)
        ->build();

    $filePath = sprintf(
        '%s.csv',
        tempnam(sys_get_temp_dir(), 'criteria-report-')
    );
    self::runExample($session, $filePath);
  }
}

DownloadCriteriaReportWithSelector::main();

Old

<?php
/**
 * This example downloads a criteria report to a file.
 *
 * Copyright 2016, Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package    GoogleApiAdsAdWords
 * @subpackage v201705
 * @category   WebServices
 * @copyright  2016, Google Inc. All Rights Reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License,
 *             Version 2.0
 */

// Include the initialization file
require_once dirname(dirname(__FILE__)) . '/init.php';
require_once ADWORDS_UTIL_VERSION_PATH . '/ReportUtils.php';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $filePath the path of the file to download the report to
 */
function DownloadCriteriaReportExample(AdWordsUser $user, $filePath) {
  // Load the service, so that the required classes are available.
  $user->LoadService('ReportDefinitionService', ADWORDS_VERSION);
  // Optional: Set clientCustomerId to get reports of your child accounts
  // $user->SetClientCustomerId('INSERT_CLIENT_CUSTOMER_ID_HERE');

  // Create selector.
  $selector = new Selector();
  $selector->fields = array('CampaignId', 'AdGroupId', 'Id', 'Criteria',
      'CriteriaType', 'Impressions', 'Clicks', 'Cost');

  // Optional: use predicate to filter out paused criteria.
  $selector->predicates[] = new Predicate('Status', 'NOT_IN', array('PAUSED'));

  // Create report definition.
  $reportDefinition = new ReportDefinition();
  $reportDefinition->selector = $selector;
  $reportDefinition->reportName = 'Criteria performance report #' . uniqid();
  $reportDefinition->dateRangeType = 'LAST_7_DAYS';
  $reportDefinition->reportType = 'CRITERIA_PERFORMANCE_REPORT';
  $reportDefinition->downloadFormat = 'CSV';

  // Set additional options.
  $options = array('version' => ADWORDS_VERSION);

  // Optional: Set skipReportHeader, skipColumnHeader, skipReportSummary to
  //     suppress headers or summary rows.
  // $options['skipReportHeader'] = true;
  // $options['skipColumnHeader'] = true;
  // $options['skipReportSummary'] = true;
  //
  // Optional: Set useRawEnumValues to return enum values instead of enum
  //     display values.
  // $options['useRawEnumValues'] = true;
  //
  // Optional: Set includeZeroImpressions to include zero impression rows in
  //     the report output.
  // $options['includeZeroImpressions'] = true;

  // Download report.
  $reportUtils = new ReportUtils();
  $reportUtils->DownloadReport($reportDefinition, $filePath, $user, $options);
  printf("Report with name '%s' was downloaded to '%s'.\n",
      $reportDefinition->reportName, $filePath);
}

// Don't run the example if the file is being included.
if (__FILE__ != realpath($_SERVER['PHP_SELF'])) {
  return;
}

try {
  // Get AdWordsUser from credentials in "../auth.ini"
  // relative to the AdWordsUser.php file's directory.
  $user = new AdWordsUser();

  // Log every SOAP XML request and response.
  $user->LogAll();

  // Download the report to a file in the same directory as the example.
  $filePath = dirname(__FILE__) . '/report.csv';

  // Run the example.
  DownloadCriteriaReportExample($user, $filePath);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Download a criteria performance report with AWQL

New

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201705\Reporting;

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

use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\Reporting\v201705\ReportDownloader;
use Google\AdsApi\AdWords\Reporting\v201705\DownloadFormat;
use Google\AdsApi\AdWords\ReportSettingsBuilder;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * Downloads CRITERIA_PERFORMANCE_REPORT for the specified client customer ID.
 */
class DownloadCriteriaReportWithAwql {

  public static function runExample(AdWordsSession $session, $reportFormat) {
    // Create report query to get the data for last 7 days.
    $reportQuery = 'SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, '
        . 'Impressions, Clicks, Cost FROM CRITERIA_PERFORMANCE_REPORT '
        . 'WHERE Status IN [ENABLED, PAUSED] DURING LAST_7_DAYS';

    // Download report as a string.
    $reportDownloader = new ReportDownloader($session);
    $reportDownloadResult = $reportDownloader->downloadReportWithAwql(
        $reportQuery, $reportFormat);
    print "Report was downloaded and printed below:\n";
    print $reportDownloadResult->getAsString();
  }

  public static function main() {
    // Generate a refreshable OAuth2 credential for authentication.
    $oAuth2Credential = (new OAuth2TokenBuilder())
        ->fromFile()
        ->build();

    // See: ReportSettingsBuilder for more options (e.g., suppress headers)
    // or set them in your adsapi_php.ini file.
    $reportSettings = (new ReportSettingsBuilder())
        ->fromFile()
        ->includeZeroImpressions(false)
        ->build();

    // See: AdWordsSessionBuilder for setting a client customer ID that is
    // different from that specified in your adsapi_php.ini file.
    // Construct an API session configured from a properties file and the OAuth2
    // credentials above.
    $session = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->withReportSettings($reportSettings)
        ->build();

    self::runExample($session, DownloadFormat::CSV);
  }
}

DownloadCriteriaReportWithAwql::main();

Old

<?php
/**
 * This example downloads a criteria report to a file.
 *
 * Copyright 2016, Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package    GoogleApiAdsAdWords
 * @subpackage v201705
 * @category   WebServices
 * @copyright  2016, Google Inc. All Rights Reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License,
 *             Version 2.0
 */

error_reporting(E_STRICT | E_ALL);

// Include the initialization file
require_once dirname(dirname(__FILE__)) . '/init.php';
require_once ADWORDS_UTIL_VERSION_PATH . '/ReportUtils.php';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $filePath the path of the file to download the report to
 */
function DownloadCriteriaReportWithAwqlExample(AdWordsUser $user, $filePath,
    $reportFormat) {
  // Optional: Set clientCustomerId to get reports of your child accounts
  // $user->SetClientCustomerId('INSERT_CLIENT_CUSTOMER_ID_HERE');

  // Prepare a date range for the last week. Instead you can use 'LAST_7_DAYS'.
  $dateRange = sprintf('%d,%d',
      date('Ymd', strtotime('-7 day')), date('Ymd', strtotime('-1 day')));

  // Create report query.
  $reportQuery = 'SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, '
      . 'Impressions, Clicks, Cost FROM CRITERIA_PERFORMANCE_REPORT '
      . 'WHERE Status IN [ENABLED, PAUSED] DURING ' . $dateRange;

  // Set additional options.
  $options = array('version' => ADWORDS_VERSION);

  // Optional: Set skipReportHeader, skipColumnHeader, skipReportSummary to
  //     suppress headers or summary rows.
  // $options['skipReportHeader'] = true;
  // $options['skipColumnHeader'] = true;
  // $options['skipReportSummary'] = true;
  //
  // Optional: Set useRawEnumValues to return enum values instead of enum
  //     display values.
  // $options['useRawEnumValues'] = false;
  //
  // Optional: Set includeZeroImpressions to include zero impression rows in
  //     the report output.
  // $options['includeZeroImpressions'] = true;

  // Download report.
  $reportUtils = new ReportUtils();
  $reportUtils->DownloadReportWithAwql($reportQuery, $filePath, $user,
      $reportFormat, $options);

  printf("Report was downloaded to '%s'.\n", $filePath);
}

// Don't run the example if the file is being included.
if (__FILE__ != realpath($_SERVER['PHP_SELF'])) {
  return;
}

try {
  // Get AdWordsUser from credentials in "../auth.ini"
  // relative to the AdWordsUser.php file's directory.
  $user = new AdWordsUser();

  // Log every SOAP XML request and response.
  $user->LogAll();

  // Download the report to a file in the same directory as the example.
  $filePath = dirname(__FILE__) . '/report.csv';
  $reportFormat = 'CSV';

  // Run the example.
  DownloadCriteriaReportWithAwqlExample($user, $filePath, $reportFormat);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Get report fields

New

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201705\Reporting;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\cm\ReportDefinitionReportType;
use Google\AdsApi\AdWords\v201705\cm\ReportDefinitionService;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example gets the fields available in a campaign report.
 */
class GetReportFields {

  const PAGE_LIMIT = 500;

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session) {
    $reportDefinitionService =
        $adWordsServices->get($session, ReportDefinitionService::class);

    // The type of the report to get fields for.
    $reportType = ReportDefinitionReportType::CAMPAIGN_PERFORMANCE_REPORT;

    // Get report fields of the report type.
    $reportDefinitionFields =
        $reportDefinitionService->getReportFields($reportType);

    printf("The report type '%s' contains the following fields:\n",
        $reportType);
    foreach ($reportDefinitionFields as $reportDefinitionField) {
      printf('  %s (%s)', $reportDefinitionField->getFieldName(),
          $reportDefinitionField->getFieldType());
      if ($reportDefinitionField->getEnumValues() !== null) {
        printf(' := [%s]',
            implode(', ', $reportDefinitionField->getEnumValues()));
      }
      print "\n";
    }
  }

  public static function main() {
    // Generate a refreshable OAuth2 credential for authentication.
    $oAuth2Credential = (new OAuth2TokenBuilder())
        ->fromFile()
        ->build();

    // Construct an API session configured from a properties file and the OAuth2
    // credentials above.
    $session = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->build();
    self::runExample(new AdWordsServices(), $session);
  }
}

GetReportFields::main();

Old

<?php
/**
 * This example gets the fields available in a campaign report.
 *
 * Copyright 2016, Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package    GoogleApiAdsAdWords
 * @subpackage v201705
 * @category   WebServices
 * @copyright  2016, Google Inc. All Rights Reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License,
 *             Version 2.0
 */

// Include the initialization file
require_once dirname(dirname(__FILE__)) . '/init.php';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 */
function GetReportFieldsExample(AdWordsUser $user) {
  // Get the service, which loads the required classes.
  $reportDefinitionService =
      $user->GetService('ReportDefinitionService', ADWORDS_VERSION);

  // The type of the report to get fields for.
  $reportType = 'CAMPAIGN_PERFORMANCE_REPORT';

  // Get report fields.
  $reportDefinitionFields =
      $reportDefinitionService->getReportFields($reportType);

  // Display results.
  printf("The report type '%s' contains the following fields:\n", $reportType);
  foreach ($reportDefinitionFields as $reportDefinitionField) {
    printf('  %s (%s)', $reportDefinitionField->fieldName,
        $reportDefinitionField->fieldType);
    if (isset($reportDefinitionField->enumValues)) {
      printf(' := [%s]', implode(', ', $reportDefinitionField->enumValues));
    }
    print "\n";
  }
}

// Don't run the example if the file is being included.
if (__FILE__ != realpath($_SERVER['PHP_SELF'])) {
  return;
}

try {
  // Get AdWordsUser from credentials in "../auth.ini"
  // relative to the AdWordsUser.php file's directory.
  $user = new AdWordsUser();

  // Log every SOAP XML request and response.
  $user->LogAll();

  // Run the example.
  GetReportFieldsExample($user);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Parallel report download

New

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201705\Reporting;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\ReportSettings;
use Google\AdsApi\AdWords\ReportSettingsBuilder;
use Google\AdsApi\AdWords\Reporting\v201705\DownloadFormat;
use Google\AdsApi\AdWords\Reporting\v201705\ReportDefinition;
use Google\AdsApi\AdWords\Reporting\v201705\ReportDefinitionDateRangeType;
use Google\AdsApi\AdWords\Reporting\v201705\ReportDownloader;
use Google\AdsApi\AdWords\v201705\cm\ApiException;
use Google\AdsApi\AdWords\v201705\cm\Paging;
use Google\AdsApi\AdWords\v201705\cm\Predicate;
use Google\AdsApi\AdWords\v201705\cm\PredicateOperator;
use Google\AdsApi\AdWords\v201705\cm\ReportDefinitionReportType;
use Google\AdsApi\AdWords\v201705\cm\Selector;
use Google\AdsApi\AdWords\v201705\mcm\ManagedCustomerService;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example gets and downloads an Ad Hoc report from an XML report
 * definition for all accounts directly under a manager account.
 * This example should be run against an AdWords manager account.
 *
 * Although the example's name is `ParallelReportDownload`, it doesn't download
 * reports in parallel as this client library doesn't support multithreading.
 * It is named so to be consistent with other client libraries.
 */
class ParallelReportDownload {

  // Timeout between retries in seconds.
  const BACKOFF_FACTOR = 5;

  // Maximum number of retries for 500 errors.
  const MAX_RETRIES = 5;

  // The number of entries per page of the results.
  const PAGE_LIMIT = 500;

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSessionBuilder $sessionBuilder, $reportDir) {
    // Construct an API session for the client customer ID specified in the
    // configuration file.
    $session = $sessionBuilder->build();

    // Create selector.
    $selector = new Selector();
    $selector->setFields(
        ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', 'Cost']);

    // Create report definition.
    $reportDefinition = new ReportDefinition();
    $reportDefinition->setSelector($selector);
    $reportDefinition->setReportName('Custom ADGROUP_PERFORMANCE_REPORT');
    $reportDefinition->setDateRangeType(
        ReportDefinitionDateRangeType::LAST_7_DAYS);
    $reportDefinition->setReportType(
        ReportDefinitionReportType::ADGROUP_PERFORMANCE_REPORT);
    $reportDefinition->setDownloadFormat(DownloadFormat::CSV);

    $customerIds = self::getAllManagedCustomerIds($adWordsServices, $session);
    printf("Downloading reports for %d managed customers.\n",
        count($customerIds));

    $successfulReports = [];
    $failedReports = [];

    foreach ($customerIds as $customerId) {
      $filePath = sprintf('%s%sadgroup_%d.csv', $reportDir,
          DIRECTORY_SEPARATOR, $customerId);

      // Construct an API session for the specified client customer ID.
      $session = $sessionBuilder->withClientCustomerId($customerId)->build();
      $reportDownloader = new ReportDownloader($session);

      $retryCount = 0;
      $doContinue = true;
      do {
        $retryCount++;
        try {
          $reportDownloadResult =
              $reportDownloader->downloadReport($reportDefinition);
          $reportDownloadResult->saveToFile($filePath);
          printf(
              "Report for client customer ID %d successfully downloaded to: "
                  . "%s\n",
              $customerId,
              $filePath
          );
          $successfulReports[$customerId] = $filePath;
          $doContinue = false;
        } catch (ApiException $e) {
          printf(
              "Report attempt #%d for client customer ID %d was not downloaded"
                  . " due to: %s\n",
              $retryCount,
              $customerId,
              $e->getMessage()
          );

          // If this is a server error, retry up to the defined maximum number
          // of retries.
          if ($e->getErrors() === null && $retryCount < self::MAX_RETRIES) {
            $sleepTime = $retryCount * self::BACKOFF_FACTOR;
            printf(
                "Sleeping %d seconds before retrying report for client customer"
                    . " ID %d.\n",
                $sleepTime,
                $customerId
            );
            sleep($sleepTime);
          } else {
            printf(
                "Report request failed for client customer ID %d.\n",
                $customerId
            );
            $failedReports[$customerId] = $filePath;
            $doContinue = false;
          }
        }
      } while ($doContinue === true);
    }

    print "All downloads completed. Results:\n";
    print "Successful reports:\n";
    foreach ($successfulReports as $customerId => $filePath) {
      printf("\tClient ID %d => '%s'\n", $customerId, $filePath);
    }
    print "Failed reports:\n";
    foreach ($failedReports as $customerId => $filePath) {
      printf("\tClient ID %d => '%s'\n", $customerId, $filePath);
    }
    print "End of results.\n";
  }

  /**
   * Retrieves all the customer IDs under a manager account.
   *
   * To set clientCustomerId to any manager account you want to get
   * reports for its client accounts, use `AdWordsSessionBuilder` to
   * create new session.
   */
  private static function getAllManagedCustomerIds(
      AdWordsServices $adWordsServices, AdWordsSession $session) {
    $managedCustomerService =
        $adWordsServices->get($session, ManagedCustomerService::class);

    $selector = new Selector();
    $selector->setFields(['CustomerId']);
    $selector->setPaging(new Paging(0, self::PAGE_LIMIT));
    $selector->setPredicates([new Predicate('CanManageClients',
        PredicateOperator::EQUALS, ['false'])]);

    $customerIds = [];
    do {
      $page = $managedCustomerService->get($selector);
      if ($page->getEntries() !== null) {
        $totalNumEntries = $page->getTotalNumEntries();
        foreach ($page->getEntries() as $customer) {
          $customerIds[] = $customer->getCustomerId();
        }
      }
      $selector->getPaging()->setStartIndex(
          $selector->getPaging()->getStartIndex() + self::PAGE_LIMIT);
    } while ($selector->getPaging()->getStartIndex() < $totalNumEntries);

    return $customerIds;
  }

  public static function main() {
    // Generate a refreshable OAuth2 credential for authentication.
    $oAuth2Credential = (new OAuth2TokenBuilder())
        ->fromFile()
        ->build();

    // See: ReportSettingsBuilder for more options (e.g., suppress headers)
    // or set them in your adsapi_php.ini file.
    $reportSettings = (new ReportSettingsBuilder())
        ->fromFile()
        ->includeZeroImpressions(false)
        ->build();

    // See: AdWordsSessionBuilder for setting a client customer ID that is
    // different from that specified in your adsapi_php.ini file.
    $sessionBuilder = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->withReportSettings($reportSettings);

    self::runExample(new AdWordsServices(), $sessionBuilder,
        sys_get_temp_dir());
  }
}

ParallelReportDownload::main();

Old

<?php
/**
 * This example gets and downloads an Ad Hoc report from an XML report
 * definition for all accounts directly under a manager account.
 * This example should be run against an AdWords manager account.
 *
 * Although the example's name is `ParallelReportDownload`, it doesn't download
 * reports in parallel as this client lib isn't built to support multithreading.
 * It is named so to be consistent with other client libs.
 *
 * Copyright 2016, Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package    GoogleApiAdsAdWords
 * @subpackage v201705
 * @category   WebServices
 * @copyright  2016, Google Inc. All Rights Reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License,
 *             Version 2.0
 */

require_once dirname(dirname(__FILE__)) . '/init.php';
require_once ADWORDS_UTIL_VERSION_PATH . '/ReportUtils.php';
define('MAX_RETRIES', 5);
define('BACKOFF_FACTOR', 5);

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 */
function ParallelReportDownloadExample(AdWordsUser $user) {
  // Load the service, so that the required classes are available.
  $user->LoadService('ReportDefinitionService', ADWORDS_VERSION);

  // Create selector.
  $selector = new Selector();
  $selector->fields =
      array('CampaignId', 'AdGroupId', 'Impressions', 'Clicks', 'Cost');

  // Create report definition.
  $reportDefinition = new ReportDefinition();
  $reportDefinition->selector = $selector;
  $reportDefinition->reportName = 'Custom ADGROUP_PERFORMANCE_REPORT';
  $reportDefinition->dateRangeType = 'LAST_7_DAYS';
  $reportDefinition->reportType = 'ADGROUP_PERFORMANCE_REPORT';
  $reportDefinition->downloadFormat = 'CSV';

  // Set additional options.
  $options = array('version' => ADWORDS_VERSION);

  // Optional: Set skipReportHeader, skipColumnHeader, skipReportSummary to
  //     suppress headers or summary rows.
  // $options['skipReportHeader'] = true;
  // $options['skipColumnHeader'] = true;
  // $options['skipReportSummary'] = true;
  //
  // Optional: Set useRawEnumValues to return enum values instead of enum
  //     display values.
  // $options['useRawEnumValues'] = true;
  //
  // Optional: Set includeZeroImpressions to include zero impression rows in
  //     the report output.
  // $options['includeZeroImpressions'] = true;

  $customerIds = getAllManagedCustomerIds($user);
  printf("Downloading reports for %d managed customers.\n",
      count($customerIds));

  $successfulReports = array();
  $failedReports = array();
  $reportDir = sys_get_temp_dir();
  $reportUtils = new ReportUtils();

  foreach ($customerIds as $customerId) {
    $filePath = sprintf('%s.csv', tempnam($reportDir, 'adgroup_'));
    $user->SetClientCustomerId($customerId);

    $retryCount = 0;
    $doContinue = true;
    do {
      $retryCount++;
      try {
        $reportUtils->DownloadReport($reportDefinition, $filePath, $user,
            $options);
        printf(
            "Report for client customer ID %d successfully downloaded to: %s\n",
            $customerId,
            $filePath
        );
        $successfulReports[$customerId] = $filePath;
        $doContinue = false;
      } catch (ReportDownloadException $e) {
        printf(
            "Report attempt #%d for client customer ID %d was not downloaded"
                . " due to: %s\n",
            $retryCount,
            $customerId,
            $e->getMessage()
        );

        if ($e->GetHttpCode() >= 500 && $retryCount < MAX_RETRIES) {
          $sleepTime = $retryCount * BACKOFF_FACTOR;
          printf(
              "Sleeping %d seconds before retrying report for client customer "
                  . "ID %d.\n",
              $sleepTime,
              $customerId
          );
          sleep($sleepTime);
        } else {
          printf(
              "Report request failed for client customer ID %d.\n",
              $customerId
          );
          $failedReports[$customerId] = $filePath;
          $doContinue = false;
        }

      }
    } while ($doContinue === true);
  }

  print "All downloads completed. Results:\n";
  print "Successful reports:\n";
  foreach ($successfulReports as $customerId => $filePath) {
    printf("\tClient ID %d => '%s'\n", $customerId, $filePath);
  }
  print "Failed reports:\n";
  foreach ($failedReports as $customerId => $filePath) {
    printf("\tClient ID %d => '%s'\n", $customerId, $filePath);
  }
  print "End of results.\n";
}

/**
 * Retrieves all the customer IDs under a manager account.
 *
 * @param AdWordsUser $user the user to run the example with
 * @return array the list of customer IDs under a manager account
 */
function getAllManagedCustomerIds(AdWordsUser $user) {
  // Optional: Set clientCustomerId to any manager account you want to get
  //     reports for its client accounts.
  // $user->SetClientCustomerId('INSERT_CLIENT_CUSTOMER_ID_HERE');
  $managedCustomerService =
      $user->GetService('ManagedCustomerService', ADWORDS_VERSION);

  $selector = new Selector();
  $selector->fields = array('CustomerId');
  $selector->paging = new Paging(0, AdWordsConstants::RECOMMENDED_PAGE_SIZE);
  $selector->predicates[] =
      new Predicate('CanManageClients', 'EQUALS', 'false');

  $customerIds = array();
  do {
    $page = $managedCustomerService->get($selector);
    if (isset($page->entries)) {
      foreach ($page->entries as $customer) {
        $customerIds[] = $customer->customerId;
      }
    }
    $selector->paging->startIndex += AdWordsConstants::RECOMMENDED_PAGE_SIZE;
  } while ($selector->paging->startIndex < $page->totalNumEntries);

  return $customerIds;
}

// Don't run the example if the file is being included.
if (__FILE__ != realpath($_SERVER['PHP_SELF'])) {
  return;
}

try {
  // Get AdWordsUser from credentials in "../auth.ini"
  // relative to the AdWordsUser.php file's directory.
  $user = new AdWordsUser();

  // Log every SOAP XML request and response.
  $user->LogAll();

  // Run the example.
  ParallelReportDownloadExample($user);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Send feedback about...

AdWords API
AdWords API
Need help? Visit our support page.