The AdWords API will sunset on April 27, 2022. Migrate to the Google Ads API to take advantage of the latest Google Ads features.

Optimization Samples

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

Get keyword traffic estimates

<?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\v201809\Optimization;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201809\cm\Keyword;
use Google\AdsApi\AdWords\v201809\cm\KeywordMatchType;
use Google\AdsApi\AdWords\v201809\cm\Language;
use Google\AdsApi\AdWords\v201809\cm\Location;
use Google\AdsApi\AdWords\v201809\cm\Money;
use Google\AdsApi\AdWords\v201809\o\AdGroupEstimateRequest;
use Google\AdsApi\AdWords\v201809\o\CampaignEstimateRequest;
use Google\AdsApi\AdWords\v201809\o\KeywordEstimateRequest;
use Google\AdsApi\AdWords\v201809\o\StatsEstimate;
use Google\AdsApi\AdWords\v201809\o\TrafficEstimatorSelector;
use Google\AdsApi\AdWords\v201809\o\TrafficEstimatorService;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example gets traffic estimates for new keywords.
 */
class EstimateKeywordTraffic
{

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

        // Create keywords. Up to 2000 keywords can be passed in a single request.
        $keywords = [];

        $keyword = new Keyword();
        $keyword->setText('mars cruise');
        $keyword->setMatchType(KeywordMatchType::BROAD);
        $keywords[] = $keyword;

        $keyword = new Keyword();
        $keyword->setText('cheap cruise');
        $keyword->setMatchType(KeywordMatchType::PHRASE);
        $keywords[] = $keyword;

        $keyword = new Keyword();
        $keyword->setText('cruise');
        $keyword->setMatchType(KeywordMatchType::EXACT);
        $keywords[] = $keyword;

        // Create a keyword estimate request for each keyword.
        $keywordEstimateRequests = [];
        foreach ($keywords as $keyword) {
            $keywordEstimateRequest = new KeywordEstimateRequest();
            $keywordEstimateRequest->setKeyword($keyword);
            $keywordEstimateRequests[] = $keywordEstimateRequest;
        }

        // Negative keywords don't return estimates, but adjust the estimates of the
        // other keywords in the hypothetical ad group.
        $negativeKeywords = [];

        $keyword = new Keyword();
        $keyword->setText('moon walk');
        $keyword->setMatchType(KeywordMatchType::BROAD);
        $negativeKeywords[] = $keyword;

        // Create a keyword estimate request for each negative keyword.
        foreach ($negativeKeywords as $negativeKeyword) {
            $keywordEstimateRequest = new KeywordEstimateRequest();
            $keywordEstimateRequest->setKeyword($negativeKeyword);
            $keywordEstimateRequest->setIsNegative(true);
            $keywordEstimateRequests[] = $keywordEstimateRequest;
        }

        // Create ad group estimate requests.
        $adGroupEstimateRequest = new AdGroupEstimateRequest();
        $adGroupEstimateRequest->setKeywordEstimateRequests(
            $keywordEstimateRequests
        );
        $money = new Money();
        $money->setMicroAmount(1000000);
        $adGroupEstimateRequest->setMaxCpc($money);

        // Create campaign estimate requests.
        $campaignEstimateRequest = new CampaignEstimateRequest();
        $campaignEstimateRequest->setAdGroupEstimateRequests(
            [$adGroupEstimateRequest]
        );

        // Optional: Set additional criteria for filtering estimates.
        // See http://code.google.com/apis/adwords/docs/appendix/countrycodes.html
        // for a detailed list of country codes.
        // Set targeting criteria. Only locations and languages are supported.
        $unitedStates = new Location();
        $unitedStates->setId(2840);

        // See http://code.google.com/apis/adwords/docs/appendix/languagecodes.html
        // for a detailed list of language codes.
        $english = new Language();
        $english->setId(1000);

        $campaignEstimateRequest->setCriteria([$unitedStates, $english]);

        // Create selector.
        $selector = new TrafficEstimatorSelector();
        $selector->setCampaignEstimateRequests([$campaignEstimateRequest]);

        // Optional: Request a list of campaign level estimates segmented by
        // platform.
        $selector->setPlatformEstimateRequested(true);

        $result = $trafficEstimatorService->get($selector);

        $platformEstimates = $result->getCampaignEstimates()[0]->getPlatformEstimates();
        if ($platformEstimates !== null) {
            foreach ($platformEstimates as $platformEstimate) {
                if ($platformEstimate->getMinEstimate() !== null
                    && $platformEstimate->getMaxEstimate() !== null) {
                    printf(
                        "Results for the platform with ID %d and name '%s':\n",
                        $platformEstimate->getPlatform()->getId(),
                        $platformEstimate->getPlatform()->getPlatformName()
                    );
                    self::printMeanEstimate(
                        $platformEstimate->getMinEstimate(),
                        $platformEstimate->getMaxEstimate()
                    );
                }
            }
        }

        $keywordEstimates = $result->getCampaignEstimates()[0]->getAdGroupEstimates()[0]->getKeywordEstimates();
        $estimatesCount = count($keywordEstimates);
        for ($i = 0; $i < $estimatesCount; $i++) {
            $keywordEstimateRequest = $keywordEstimateRequests[$i];
            // Skip negative keywords, since they don't return estimates.
            if ($keywordEstimateRequest->getIsNegative() !== true) {
                $keyword = $keywordEstimateRequest->getKeyword();
                $keywordEstimate = $keywordEstimates[$i];

                if ($keywordEstimate->getMin() !== null
                    && $keywordEstimate->getMax() !== null) {
                    // Print the mean of the min and max values.
                    printf(
                        "Results for the keyword with text '%s' and match type '%s':\n",
                        $keyword->getText(),
                        $keyword->getMatchType()
                    );
                    self::printMeanEstimate(
                        $keywordEstimate->getMin(),
                        $keywordEstimate->getMax()
                    );
                }
            }
        }
    }

    /**
     * Prints estimated average CPC, ad position, daily clicks, and daily costs
     * between the provided lower bound and upper bound of estimated stats.
     *
     * @param StatsEstimate $minEstimate the lower bound on the estimated stats
     * @param StatsEstimate $maxEstimate the upper bound on the estimated stats
     */
    private static function printMeanEstimate(
        StatsEstimate $minEstimate,
        StatsEstimate $maxEstimate
    ) {
        $meanAverageCpc = self::calculateMeanMicroAmount(
            $minEstimate->getAverageCpc(),
            $maxEstimate->getAverageCpc()
        );

        $meanAveragePosition = self::calculateMean(
            $minEstimate->getAveragePosition(),
            $maxEstimate->getAveragePosition()
        );

        $meanClicks = self::calculateMean(
            $minEstimate->getClicksPerDay(),
            $maxEstimate->getClicksPerDay()
        );

        $meanTotalCost = self::calculateMeanMicroAmount(
            $minEstimate->getTotalCost(),
            $maxEstimate->getTotalCost()
        );

        printf(
            " Estimated average CPC: %s\n",
            self::formatMean($meanAverageCpc)
        );
        printf(
            " Estimated ad position: %s\n",
            self::formatMean($meanAveragePosition)
        );
        printf(" Estimated daily clicks: %s\n", self::formatMean($meanClicks));
        printf(
            " Estimated daily cost: %s\n\n",
            self::formatMean($meanTotalCost)
        );
    }

    /**
     * Returns the mean of the two numbers if neither is null, else returns null.
     */
    private static function calculateMean($min, $max)
    {
        if ($min === null || $max === null) {
            return null;
        }

        return ($min + $max) / 2;
    }

    /**
     * Returns the mean of the two object's microAmounts if neither is null, else
     * returns null.
     */
    private static function calculateMeanMicroAmount($min, $max)
    {
        if ($min === null || $max === null) {
            return null;
        }
        if ($min->getMicroAmount() === null
            || $max->getMicroAmount() === null) {
            return null;
        }

        return ($min->getMicroAmount() + $max->getMicroAmount()) / 2;
    }

    /**
     * Returns a formatted version of the mean value, handling nulls.
     */
    private static function formatMean($mean)
    {
        if ($mean === null) {
            return 'null';
        }

        return sprintf("%.2f", $mean);
    }

    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);
    }
}

EstimateKeywordTraffic::main();

Get all mobile bid modifier landscapes for a campaign

<?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\v201809\Optimization;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201809\cm\DataService;
use Google\AdsApi\AdWords\v201809\cm\Paging;
use Google\AdsApi\AdWords\v201809\cm\Predicate;
use Google\AdsApi\AdWords\v201809\cm\PredicateOperator;
use Google\AdsApi\AdWords\v201809\cm\Selector;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example gets all available campaign mobile bid modifier landscapes
 * for a given campaign.
 * To get campaigns, run BasicOperations/GetCampaigns.php.
 */
class GetCampaignCriterionBidModifierSimulations
{

    const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';
    const PAGE_SIZE = 100;

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

        // Create a selector to select all campaign criterion bid modifiers for the
        // specified campaign.
        $selector = new Selector();
        $selector->setFields(
            [
                'BidModifier',
                'CampaignId',
                'CriterionId',
                'StartDate',
                'EndDate',
                'LocalClicks',
                'LocalCost',
                'LocalImpressions',
                'TotalLocalClicks',
                'TotalLocalCost',
                'TotalLocalImpressions',
                'RequiredBudget'
            ]
        );
        $selector->setPredicates(
            [new Predicate('CampaignId', PredicateOperator::IN, [$campaignId])]
        );
        $selector->setPaging(new Paging(0, self::PAGE_SIZE));

        // Display bid landscapes.
        $landscapePointsInPreviousPage = 0;
        $startIndex = 0;
        do {
            // Offset the start index by the number of landscape points in the last
            // retrieved page, NOT the number of entries (bid landscapes) in the page.
            $startIndex += $landscapePointsInPreviousPage;
            $selector->getPaging()->setStartIndex($startIndex);

            // Reset the count of landscape points in preparation for processing the
            // next page.
            $landscapePointsInPreviousPage = 0;

            // Retrieve campaign criterion bid modifiers one page at a time,
            // continuing to request pages until all of them have been retrieved.
            $page = $dataService->getCampaignCriterionBidLandscape($selector);

            // Print out some information for each campaign criterion bid modifier.
            if ($page->getEntries() !== null) {
                foreach ($page->getEntries() as $bidModifierLandscape) {
                    printf(
                        "Found campaign-level criterion bid modifier landscapes for"
                        . " criterion with ID %d, start date '%s', end date '%s', and landscape points:\n",
                        $bidModifierLandscape->getCriterionId(),
                        $bidModifierLandscape->getStartDate(),
                        $bidModifierLandscape->getEndDate()
                    );
                    $landscapePointsInPreviousPage = count($bidModifierLandscape->getLandscapePoints());
                    foreach ($bidModifierLandscape->getLandscapePoints() as $landscapePoint) {
                        printf(
                            "  bid modifier: %.2f => clicks: %d, cost: %d, "
                            . "impressions: %d, total clicks: %d, total cost: %d, "
                            . "total impressions: %d, and required budget: %d\n",
                            $landscapePoint->getBidModifier(),
                            $landscapePoint->getClicks(),
                            $landscapePoint->getCost()->getMicroAmount(),
                            $landscapePoint->getImpressions(),
                            $landscapePoint->getTotalLocalClicks(),
                            $landscapePoint->getTotalLocalCost()->getMicroAmount(),
                            $landscapePoint->getTotalLocalImpressions(),
                            $landscapePoint->getRequiredBudget()->getMicroAmount()
                        );
                    }
                    print "\n";
                }
            }
        } while ($landscapePointsInPreviousPage >= self::PAGE_SIZE);
    }

    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,
            intval(self::CAMPAIGN_ID)
        );
    }
}

GetCampaignCriterionBidModifierSimulations::main();

Get a bid landscape for an ad group and criterion

<?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\v201809\Optimization;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\Query\v201809\ServiceQueryBuilder;
use Google\AdsApi\AdWords\v201809\cm\DataService;
use Google\AdsApi\AdWords\v201809\cm\Paging;
use Google\AdsApi\AdWords\v201809\cm\Predicate;
use Google\AdsApi\AdWords\v201809\cm\PredicateOperator;
use Google\AdsApi\AdWords\v201809\cm\Selector;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example gets all available keyword bid simulations within an ad group.
 * To get ad groups, run BasicOperation/GetAdGroups.php.
 */
class GetKeywordBidSimulations
{

    const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';
    const PAGE_SIZE = 100;

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

        // Create a query to select all keyword bid simulations for the
        // specified ad group.
        $query = (new ServiceQueryBuilder())
            ->select([
                'AdGroupId',
                'CriterionId',
                'StartDate',
                'EndDate',
                'Bid',
                'BiddableConversions',
                'BiddableConversionsValue',
                'LocalClicks',
                'LocalCost',
                'LocalImpressions'
            ])
            ->where('AdGroupId')->in([$adGroupId])
            ->limit(0, self::PAGE_SIZE)
            ->build();

        // Display bid landscapes.
        do {
            if (isset($fetchedPage)) {
                // Advance the paging offset in subsequent iterations only.
                $query->nextPage();
            }

            // Retrieve keyword bid simulations one page at a time, continuing
            // to request pages until all of them have been retrieved.
            $fetchedPage = $dataService->queryCriterionBidLandscape(
                sprintf('%s', $query)
            );

            // Print out some information for each bid landscape.
            if ($fetchedPage->getEntries() !== null) {
                foreach ($fetchedPage->getEntries() as $bidLandscape) {
                    printf(
                        "Found a criterion bid landscape with ad group ID %d," .
                        " criterion ID %d, start date '%s', end date '%s'," .
                        " and landscape points:%s",
                        $bidLandscape->getAdGroupId(),
                        $bidLandscape->getCriterionId(),
                        $bidLandscape->getStartDate(),
                        $bidLandscape->getEndDate(),
                        PHP_EOL
                    );
                    foreach ($bidLandscape->getLandscapePoints() as
                             $bidLandscapePoint) {
                        printf(
                            "  bid: %d => clicks: %d, cost: %d, impressions: %d"
                            . ", biddable conversions: %.2f, biddable "
                            . "conversions value: %.2f%s",
                            $bidLandscapePoint->getBid()->getMicroAmount(),
                            $bidLandscapePoint->getClicks(),
                            $bidLandscapePoint->getCost()->getMicroAmount(),
                            $bidLandscapePoint->getImpressions(),
                            $bidLandscapePoint->getBiddableConversions(),
                            $bidLandscapePoint->getBiddableConversionsValue(),
                            PHP_EOL
                        );
                    }
                    print PHP_EOL;
                }
            }
        } while ($query->hasNext($fetchedPage));
    }

    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,
            intval(self::AD_GROUP_ID)
        );
    }
}

GetKeywordBidSimulations::main();

<?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\v201809\Optimization;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201809\cm\Language;
use Google\AdsApi\AdWords\v201809\cm\NetworkSetting;
use Google\AdsApi\AdWords\v201809\cm\Paging;
use Google\AdsApi\AdWords\v201809\o\AttributeType;
use Google\AdsApi\AdWords\v201809\o\IdeaType;
use Google\AdsApi\AdWords\v201809\o\LanguageSearchParameter;
use Google\AdsApi\AdWords\v201809\o\NetworkSearchParameter;
use Google\AdsApi\AdWords\v201809\o\RelatedToQuerySearchParameter;
use Google\AdsApi\AdWords\v201809\o\RequestType;
use Google\AdsApi\AdWords\v201809\o\SeedAdGroupIdSearchParameter;
use Google\AdsApi\AdWords\v201809\o\TargetingIdeaSelector;
use Google\AdsApi\AdWords\v201809\o\TargetingIdeaService;
use Google\AdsApi\Common\OAuth2TokenBuilder;
use Google\AdsApi\Common\Util\MapEntries;

/**
 * This example gets keyword ideas related to a seed keyword.
 */
class GetKeywordIdeas
{

    // If you do not want to use an existing ad group to seed your request, you
    // can set this to null.
    const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';
    const PAGE_LIMIT = 500;

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

        // Create selector.
        $selector = new TargetingIdeaSelector();
        $selector->setRequestType(RequestType::IDEAS);
        $selector->setIdeaType(IdeaType::KEYWORD);
        $selector->setRequestedAttributeTypes(
            [
                AttributeType::KEYWORD_TEXT,
                AttributeType::SEARCH_VOLUME,
                AttributeType::AVERAGE_CPC,
                AttributeType::COMPETITION,
                AttributeType::CATEGORY_PRODUCTS_AND_SERVICES
            ]
        );

        $paging = new Paging();
        $paging->setStartIndex(0);
        $paging->setNumberResults(10);
        $selector->setPaging($paging);

        $searchParameters = [];
        // Create related to query search parameter.
        $relatedToQuerySearchParameter = new RelatedToQuerySearchParameter();
        $relatedToQuerySearchParameter->setQueries(
            [
                'bakery',
                'pastries',
                'birthday cake'
            ]
        );
        $searchParameters[] = $relatedToQuerySearchParameter;

        // Create language search parameter (optional).
        // The ID can be found in the documentation:
        // https://developers.google.com/adwords/api/docs/appendix/languagecodes
        $languageParameter = new LanguageSearchParameter();
        $english = new Language();
        $english->setId(1000);
        $languageParameter->setLanguages([$english]);
        $searchParameters[] = $languageParameter;

        // Create network search parameter (optional).
        $networkSetting = new NetworkSetting();
        $networkSetting->setTargetGoogleSearch(true);
        $networkSetting->setTargetSearchNetwork(false);
        $networkSetting->setTargetContentNetwork(false);
        $networkSetting->setTargetPartnerSearchNetwork(false);

        $networkSearchParameter = new NetworkSearchParameter();
        $networkSearchParameter->setNetworkSetting($networkSetting);
        $searchParameters[] = $networkSearchParameter;

        // Optional: Use an existing ad group to generate ideas.
        if (!empty($adGroupId)) {
            $seedAdGroupIdSearchParameter = new SeedAdGroupIdSearchParameter();
            $seedAdGroupIdSearchParameter->setAdGroupId($adGroupId);
            $searchParameters[] = $seedAdGroupIdSearchParameter;
        }
        $selector->setSearchParameters($searchParameters);
        $selector->setPaging(new Paging(0, self::PAGE_LIMIT));

        // Get keyword ideas.
        $page = $targetingIdeaService->get($selector);

        // Print out some information for each targeting idea.
        $entries = $page->getEntries();
        if ($entries !== null) {
            foreach ($entries as $targetingIdea) {
                $data = MapEntries::toAssociativeArray($targetingIdea->getData());
                $keyword = $data[AttributeType::KEYWORD_TEXT]->getValue();
                $searchVolume = ($data[AttributeType::SEARCH_VOLUME]->getValue() !== null)
                    ? $data[AttributeType::SEARCH_VOLUME]->getValue() : 0;
                $averageCpc = $data[AttributeType::AVERAGE_CPC]->getValue();
                $competition = $data[AttributeType::COMPETITION]->getValue();
                $categoryIds = ($data[AttributeType::CATEGORY_PRODUCTS_AND_SERVICES]->getValue() === null)
                    ? $categoryIds = ''
                    : implode(
                        ', ',
                        $data[AttributeType::CATEGORY_PRODUCTS_AND_SERVICES]->getValue()
                    );
                printf(
                    "Keyword with text '%s', average monthly search volume %d, "
                    . "average CPC %d, and competition %.2f was found with categories: %s\n",
                    $keyword,
                    $searchVolume,
                    ($averageCpc === null) ? 0 : $averageCpc->getMicroAmount(),
                    $competition,
                    $categoryIds
                );
            }
        }

        if (empty($entries)) {
            print "No related keywords were found.\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, self::AD_GROUP_ID);
    }
}

GetKeywordIdeas::main();