Targeting Samples

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

Add targeting criteria to a campaign

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\Targeting;

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\CampaignCriterion;
use Google\AdsApi\AdWords\v201705\cm\CampaignCriterionOperation;
use Google\AdsApi\AdWords\v201705\cm\CampaignCriterionService;
use Google\AdsApi\AdWords\v201705\cm\ConstantOperand;
use Google\AdsApi\AdWords\v201705\cm\ConstantOperandConstantType;
use Google\AdsApi\AdWords\v201705\cm\ConstantOperandUnit;
use Google\AdsApi\AdWords\v201705\cm\FunctionOperator;
use Google\AdsApi\AdWords\v201705\cm\Keyword;
use Google\AdsApi\AdWords\v201705\cm\KeywordMatchType;
use Google\AdsApi\AdWords\v201705\cm\Location;
use Google\AdsApi\AdWords\v201705\cm\LocationExtensionOperand;
use Google\AdsApi\AdWords\v201705\cm\LocationGroups;
use Google\AdsApi\AdWords\v201705\cm\Language;
use Google\AdsApi\AdWords\v201705\cm\MatchingFunction;
use Google\AdsApi\AdWords\v201705\cm\NegativeCampaignCriterion;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds various types of targeting criteria to a campaign.
 * To get campaigns, run BasicOperations/GetCampaigns.php.
 */
class AddCampaignTargetingCrtieria {

  const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';
  // Replace the value below with the ID of a feed that has been configured for
  // location targeting, meaning it has an ENABLED FeedMapping with
  // criterionType of 77. Feeds linked to a GMB account automatically have this
  // FeedMapping. If you don't have such a feed, set this value to null.
  const LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE';

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

    $campaignCriteria = [];

    // Create locations. The IDs can be found in the documentation or retrieved
    // with the LocationCriterionService.
    $california = new Location();
    $california->setId(21137);
    $campaignCriteria[] =
        new CampaignCriterion($campaignId, null, $california);

    $mexico = new Location();
    $mexico->setId(2484);
    $campaignCriteria[] =
        new CampaignCriterion($campaignId, null, $mexico);

    // Create languages. The IDs can be found in the documentation or retrieved
    // with the ConstantDataService.
    $english = new Language();
    $english->setId(1000);
    $campaignCriteria[] =
        new CampaignCriterion($campaignId, null, $english);

    $spanish = new Language();
    $spanish->setId(1003);
    $campaignCriteria[] =
        new CampaignCriterion($campaignId, null, $spanish);

    if ($locationFeedId !== null) {
      // Distance targeting. Area of 10 miles around targets above.
      $radius = new ConstantOperand();
      $radius->setType(ConstantOperandConstantType::DOUBLE);
      $radius->setUnit(ConstantOperandUnit::MILES);
      $radius->setDoubleValue(10.0);
      $distance = new LocationExtensionOperand($radius);
      $locationGroup = new LocationGroups();
      $locationGroup->setFeedId(intval($locationFeedId));
      $locationGroup->setMatchingFunction(
          new MatchingFunction(FunctionOperator::IDENTITY, [$distance]));
      $campaignCriteria[] =
          new CampaignCriterion($campaignId, null, $locationGroup);
    }

    $operations = [];
    foreach ($campaignCriteria as $campaignCriterion) {
      $operation = new CampaignCriterionOperation();
      $operation->setOperator(Operator::ADD);
      $operation->setOperand($campaignCriterion);
      $operations[] = $operation;
    }

    // Add a negative campaign criterion.
    $negativeKeyword = new Keyword();
    $negativeKeyword->setText('jupiter cruise');
    $negativeKeyword->setMatchType(KeywordMatchType::BROAD);
    $negativeCriterion = new NegativeCampaignCriterion();
    $negativeCriterion->setCampaignId($campaignId);
    $negativeCriterion->setCriterion($negativeKeyword);

    $operation = new CampaignCriterionOperation();
    $operation->setOperator(Operator::ADD);
    $operation->setOperand($negativeCriterion);
    $operations[] = $operation;

    $result = $campaignCriterionService->mutate($operations);

    // Print out some information about added campaign criteria.
    foreach ($result->getValue() as $campaignCriterion) {
      printf(
          "Campaign targeting criterion with ID %d and type '%s' was added.\n",
          $campaignCriterion->getCriterion()->getId(),
          $campaignCriterion->getCriterion()->getType());
    }
  }

  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),
            self::LOCATION_FEED_ID);
  }
}

AddCampaignTargetingCrtieria::main();

Old

<?php
/**
 * This example adds various types of targeting criteria to a campaign. To get
 * campaigns, run BasicOperations/GetCampaigns.php.
 *
 * 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';

// Enter parameters required by the code example.
$campaignId = 'INSERT_CAMPAIGN_ID_HERE';
// Replace the value below with the ID of a feed that has been configured for
// location targeting, meaning it has an ENABLED FeedMapping with criterionType
// of 77. Feeds linked to a GMB account automatically have this FeedMapping.
// If you don't have such a feed, set this value to null.
$locationFeedId = 'INSERT_LOCATION_FEED_ID_HERE';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $campaignId the id of the campaign to add targeting criteria to
 * @param string $locationFeedId the id of a feed configured for location
 *     targeting
 */
function AddCampaignTargetingCriteriaExample(AdWordsUser $user, $campaignId,
      $locationFeedId) {
  // Get the service, which loads the required classes.
  $campaignCriterionService =
      $user->GetService('CampaignCriterionService', ADWORDS_VERSION);

  $campaignCriteria = array();

  // Create locations. The IDs can be found in the documentation or retrieved
  // with the LocationCriterionService.
  $california = new Location();
  $california->id = 21137;
  $campaignCriteria[] = new CampaignCriterion($campaignId, null, $california);

  $mexico = new Location();
  $mexico->id = 2484;
  $campaignCriteria[] = new CampaignCriterion($campaignId, null, $mexico);

  // Create languages. The IDs can be found in the documentation or retrieved
  // with the ConstantDataService.
  $english = new Language();
  $english->id = 1000;
  $campaignCriteria[] = new CampaignCriterion($campaignId, null, $english);

  $spanish = new Language();
  $spanish->id = 1003;
  $campaignCriteria[] = new CampaignCriterion($campaignId, null, $spanish);

  if ($locationFeedId !== null) {
    // Distance targeting. Area of 10 miles around targets above.
    $radius = new ConstantOperand();
    $radius->type = 'DOUBLE';
    $radius->unit = 'MILES';
    $radius->doubleValue = 10.0;
    $distance = new LocationExtensionOperand($radius);
    $locationGroup = new LocationGroups();
    $locationGroup->feedId = intval($locationFeedId);
    $locationGroup->matchingFunction = new FeedFunction('IDENTITY', $distance);
    $campaignCriteria[] =
        new CampaignCriterion($campaignId, null, $locationGroup);
  }

  // Create operations.
  $operations = array();
  foreach ($campaignCriteria as $campaignCriterion) {
    $operations[] = new CampaignCriterionOperation($campaignCriterion, 'ADD');
  }

  // Add a negative campaign criterion.
  $negativeKeyword = new Keyword();
  $negativeKeyword->text = 'jupiter cruise';
  $negativeKeyword->matchType = 'BROAD';
  $negativeCriterion = new NegativeCampaignCriterion();
  $negativeCriterion->campaignId = $campaignId;
  $negativeCriterion->criterion = $negativeKeyword;

  $operations[] = new CampaignCriterionOperation($negativeCriterion, 'ADD');

  // Make the mutate request.
  $result = $campaignCriterionService->mutate($operations);

  // Display results.
  foreach ($result->value as $campaignCriterion) {
    printf("Campaign targeting criterion with ID '%s' and type '%s' was "
        . "added.\n", $campaignCriterion->criterion->id,
        $campaignCriterion->criterion->CriterionType);
  }
}

// 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.
  AddCampaignTargetingCriteriaExample($user, $campaignId, $locationFeedId);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Get all campaign targeting criteria

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\Targeting;

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\CampaignCriterionService;
use Google\AdsApi\AdWords\v201705\cm\Predicate;
use Google\AdsApi\AdWords\v201705\cm\PredicateOperator;
use Google\AdsApi\AdWords\v201705\cm\Paging;
use Google\AdsApi\AdWords\v201705\cm\Selector;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example gets all targeting criteria for a campaign. To add targeting
 * criteria, run AddCampaignTargetingCriteria.php.
 */
class GetCampaignTargetingCriteria {

  const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';
  const PAGE_LIMIT = 500;

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

    // Create a selector to select all campaign criteria for the specified
    // campaign.
    $selector = new Selector();
    $selector->setFields(['Id', 'CriteriaType']);
    $selector->setPredicates([
        new Predicate('CampaignId', PredicateOperator::IN, [$campaignId]),
        new Predicate('CriteriaType', PredicateOperator::IN,
            ['LANGUAGE', 'LOCATION', 'AGE_RANGE', 'CARRIER',
            'OPERATING_SYSTEM_VERSION', 'GENDER', 'PROXIMITY', 'PLATFORM'])
    ]);
    $selector->setPaging(new Paging(0, self::PAGE_LIMIT));

    $totalNumEntries = 0;
    do {
      // Retrieve campaign criteria one page at a time, continuing to request
      // pages until all campaign criteria have been retrieved.
      $page = $campaignCriterionService->get($selector);

      // Print out some information for each campaign criterion.
      if ($page->getEntries() !== null) {
        $totalNumEntries = $page->getTotalNumEntries();
        foreach ($page->getEntries() as $campaignCriterion) {
          printf(
              "Campaign targeting criterion with ID %d and type '%s' was "
                  . "found.\n",
              $campaignCriterion->getCriterion()->getId(),
              $campaignCriterion->getCriterion()->getType()
          );
        }
      }

      $selector->getPaging()->setStartIndex(
          $selector->getPaging()->getStartIndex() + self::PAGE_LIMIT);
    } while ($selector->getPaging()->getStartIndex() < $totalNumEntries);

    printf("Number of results found: %d\n", $totalNumEntries);
  }

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

GetCampaignTargetingCriteria::main();

Old

<?php
/**
 * This example gets all targeting criteria for a campaign. To add targeting
 * criteria, run AddCampaignTargetingCriteria.php.
 *
 * 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';

// Enter parameters required by the code example.
$campaignId = 'INSERT_CAMPAIGN_ID_HERE';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $campaignId the ID of the campaign to get targeting criteria
 *     for
 */
function GetCampaignTargetingCriteriaExample(AdWordsUser $user, $campaignId) {
  // Get the service, which loads the required classes.
  $campaignCriterionService =
      $user->GetService('CampaignCriterionService', ADWORDS_VERSION);

  // Create selector.
  $selector = new Selector();
  $selector->fields = array('Id', 'CriteriaType');

  // Create predicates.
  $selector->predicates[] =
      new Predicate('CampaignId', 'IN', array($campaignId));
  $selector->predicates[] = new Predicate('CriteriaType', 'IN',
      array('LANGUAGE', 'LOCATION', 'AGE_RANGE', 'CARRIER',
          'OPERATING_SYSTEM_VERSION', 'GENDER', 'PROXIMITY', 'PLATFORM'));

  // Create paging controls.
  $selector->paging = new Paging(0, AdWordsConstants::RECOMMENDED_PAGE_SIZE);

  do {
    // Make the get request.
    $page = $campaignCriterionService->get($selector);

    // Display results.
    if (isset($page->entries)) {
      foreach ($page->entries as $campaignCriterion) {
        printf("Campaign targeting criterion with ID '%s' and type '%s' was "
            . "found.\n", $campaignCriterion->criterion->id,
            $campaignCriterion->criterion->CriterionType);
      }
    } else {
      print "No campaign targeting criteria were found.\n";
    }

    // Advance the paging index.
    $selector->paging->startIndex += AdWordsConstants::RECOMMENDED_PAGE_SIZE;
  } while ($page->totalNumEntries > $selector->paging->startIndex);
}

// 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.
  GetCampaignTargetingCriteriaExample($user, $campaignId);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Get all targetable languages and carriers

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\Targeting;

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\ConstantDataService;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example gets all language and carrier criteria available for targeting.
 */
class GetTargetableLanguagesAndCarriers {

  const PAGE_LIMIT = 500;

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

    // Retrieve language criteria.
    $languages = $constantDataService->getLanguageCriterion();
    foreach ($languages as $language) {
      printf("Language with name '%s' and ID %d was found.\n",
          $language->getName(), $language->getId());
    }

    print "\n";

    // Retrieve carrier criteria.
    $carriers = $constantDataService->getCarrierCriterion();
    foreach ($carriers as $carrier) {
      printf(
          "Carrier with name '%s', country code '%s', and ID %d was found.\n",
          $carrier->getName(),
          $carrier->getCountryCode(),
          $carrier->getId()
      );
    }
  }

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

GetTargetableLanguagesAndCarriers::main();

Old

<?php
/**
 * This example gets all language and carrier criteria available for targeting.
 *
 * 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 GetTargetableLanguagesAndCarriersExample(AdWordsUser $user) {
  // Get the service, which loads the required classes.
  $constantDataService = $user->GetService('ConstantDataService', ADWORDS_VERSION);

  // Make the getLanguageCriterion request.
  $languages = $constantDataService->getLanguageCriterion();

  foreach ($languages as $language) {
    printf("Language with name '%s' and ID '%s' was found.\n",
        $language->name, $language->id);
  }

  print "\n";

  // Make the getCarrierCriterion request.
  $carriers = $constantDataService->getCarrierCriterion();

  foreach ($carriers as $carrier) {
    printf("Carrier with name '%s', country code '%s', and ID '%s' was "
        . "found.\n", $carrier->name, $carrier->countryCode, $carrier->id);
  }
}

// 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.
  GetTargetableLanguagesAndCarriersExample($user);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Get location criteria by name

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\Targeting;

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\LocationCriterionService;
use Google\AdsApi\AdWords\v201705\cm\Predicate;
use Google\AdsApi\AdWords\v201705\cm\PredicateOperator;
use Google\AdsApi\AdWords\v201705\cm\Selector;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example looks up location criteria by name.
 */
class LookupLocation {

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

    // Location names to look up.
    $locationNames = ['Paris', 'Quebec', 'Spain', 'Deutschland'];
    // Locale to retrieve location names in.
    $locale = 'en';

    // Create a selector to select all locations.
    $selector = new Selector();
    $selector->setFields(['Id', 'LocationName', 'CanonicalName',
        'DisplayType',  'ParentLocations', 'Reach', 'TargetingStatus']);
    // Location names must match exactly, only EQUALS and IN are supported
    // and only one locale can be used in a request.
    $selector->setPredicates([
        new Predicate('LocationName', PredicateOperator::IN, $locationNames),
        new Predicate('Locale', PredicateOperator::EQUALS, [$locale])
    ]);

    // Retrieve location criteria from the server.
    $locationCriteria = $locationCriterionService->get($selector);

    // Print out some information for each location criterion.
    if ($locationCriteria !== null) {
      foreach ($locationCriteria as $locationCriterion) {
        if ($locationCriterion->getLocation()->getParentLocations() !== null) {
          $parentLocations = [];
          foreach ($locationCriterion->getLocation()->getParentLocations()
              as $location) {
            $parentLocations[] = sprintf(
                '%s (%s)',
                $location->getLocationName(),
                $location->getDisplayType()
            );
          }
          $parentLocationsString = implode(', ', $parentLocations);
        } else {
          $parentLocations = 'N/A';
        }
        printf(
            "The search term '%s' returned the location '%s' of type '%s' "
                . "with ID %d, parent locations '%s', and reach %d (%s).\n",
            $locationCriterion->getSearchTerm(),
            $locationCriterion->getLocation()->getLocationName(),
            $locationCriterion->getLocation()->getDisplayType(),
            $locationCriterion->getLocation()->getId(),
            $parentLocationsString,
            $locationCriterion->getReach(),
            $locationCriterion->getLocation()->getTargetingStatus()
        );
      }
    } else {
      print "No location criteria 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);
  }
}

LookupLocation::main();

Old

<?php
/**
 * This example looks up location criteria by name.
 *
 * 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';

/**
 * Gets a string representation for a location.
 * @param Location $location the location
 * @return string the string representation
 */
function GetLocationString($location) {
  return sprintf('%s (%s)', $location->locationName, $location->displayType);
}

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

  // Location names to look up.
  $locationNames = array('Paris', 'Quebec', 'Spain', 'Deutschland');
  // Locale to retrieve location names in.
  $locale = 'en';

  $selector = new Selector();
  $selector->fields = array('Id', 'LocationName', 'CanonicalName',
      'DisplayType',  'ParentLocations', 'Reach', 'TargetingStatus');
  // Location names must match exactly, only EQUALS and IN are supported.
  $selector->predicates[] = new Predicate('LocationName', 'IN', $locationNames);
  // Only one locale can be used in a request.
  $selector->predicates[] = new Predicate('Locale', 'EQUALS', $locale);

  // Make the get request.
  $locationCriteria = $locationCriterionService->get($selector);

  // Display results.
  if (isset($locationCriteria)) {
    foreach ($locationCriteria as $locationCriterion) {
      if (isset($locationCriterion->location->parentLocations)) {
        $parentLocations = implode(', ',
            array_map('GetLocationString',
                $locationCriterion->location->parentLocations));
      } else {
        $parentLocations = 'N/A';
      }
      printf("The search term '%s' returned the location '%s' of type '%s' "
          . "with ID '%s', parent locations '%s', and reach '%d' (%s).\n",
          $locationCriterion->searchTerm,
          $locationCriterion->location->locationName,
          $locationCriterion->location->displayType,
          $locationCriterion->location->id,
          $parentLocations,
          $locationCriterion->reach,
          $locationCriterion->location->targetingStatus);
    }
  } else {
    print "No location criteria were found.\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.
  LookupLocationExample($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.