Extensions Samples

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

Add Google My Business location extensions

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

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\ApiException;
use Google\AdsApi\AdWords\v201705\cm\ConstantOperand;
use Google\AdsApi\AdWords\v201705\cm\ConstantOperandConstantType;
use Google\AdsApi\AdWords\v201705\cm\CustomerFeed;
use Google\AdsApi\AdWords\v201705\cm\CustomerFeedOperation;
use Google\AdsApi\AdWords\v201705\cm\CustomerFeedService;
use Google\AdsApi\AdWords\v201705\cm\Feed;
use Google\AdsApi\AdWords\v201705\cm\MatchingFunction;
use Google\AdsApi\AdWords\v201705\cm\FeedOrigin;
use Google\AdsApi\AdWords\v201705\cm\FeedOperation;
use Google\AdsApi\AdWords\v201705\cm\FeedService;
use Google\AdsApi\AdWords\v201705\cm\FunctionOperator;
use Google\AdsApi\AdWords\v201705\cm\OAuthInfo;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\cm\PlacesLocationFeedData;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds a feed that syncs feed items from a Google
 * My Business (GMB) account and associates the feed with a customer.
 */
class AddGoogleMyBusinessLocationExtensions {

  // The placeholder type for location extensions.
  // See the Placeholder reference page for a list of all the placeholder types
  // and fields.
  // https://developers.google.com/adwords/api/docs/appendix/placeholders
  const PLACEHOLDER_LOCATION = 7;

  // The maximum number of CustomerFeed ADD operation attempts to make before
  // throwing an exception.
  const MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10;

  // The email address of either an owner or a manager of the GMB account.
  const GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS';

  // If the gmbEmailAddress above is for a GMB manager instead of the GMB
  // account owner, then set businessAccountIdentifier to the +Page ID of a
  // location for which the manager has access. See the location extensions
  // guide at https://developers.google.com/adwords/api/docs/guides/feed-services-locations
  // for details.
  const BUSINESS_ACCOUNT_IDENTIFIER = null;

  public static function runExample(
      AdWordsServices $adWordsServices,
      AdWordsSession $session,
      $gmbEmailAddress,
      $gmbAccessToken,
      $gmbBusinessAccountId
  ) {
    $feedService = $adWordsServices->get($session, FeedService::class);

    // Create a feed that will sync to the Google My Business account specified
    // by $gmbEmailAddress. Do not add FeedAttributes to this object, as AdWords
    // will add them automatically because this will be a system generated feed.
    $gmbFeed = new Feed();
    $gmbFeed->setName('Google My Business feed #' . uniqid());

    $feedData = new PlacesLocationFeedData();
    $feedData->setEmailAddress($gmbEmailAddress);
    $feedData->setBusinessAccountIdentifier($gmbBusinessAccountId);

    // Optional: specify labels to filter Google My Business listings. If
    // specified, only listings that have any of the labels set are
    // synchronized into FeedItems.
    $feedData->setLabelFilters(['Stores in New York City']);

    $oAuthInfo = new OAuthInfo();
    $oAuthInfo->setHttpMethod('GET');
    $oAuthInfo->setHttpRequestUrl('https://www.googleapis.com/auth/adwords');
    $oAuthInfo->setHttpAuthorizationHeader(
        sprintf('Bearer %s', $gmbAccessToken));
    $feedData->setOAuthInfo($oAuthInfo);

    $gmbFeed->setSystemFeedGenerationData($feedData);

    // Since this feed's feed items will be managed by AdWords,
    // you must set its origin to ADWORDS.
    $gmbFeed->setOrigin(FeedOrigin::ADWORDS);

    // Create a feed operation and add it to the list.
    $operation = new FeedOperation();
    $operation->setOperator(Operator::ADD);
    $operation->setOperand($gmbFeed);
    $operations = [$operation];

    // Add the feed on the server. Since it is a system generated feed, AdWords
    // will automatically:
    // 1. Set up the FeedAttributes on the feed.
    // 2. Set up a FeedMapping that associates the FeedAttributes of the feed
    // with the placeholder fields of the LOCATION placeholder type.
    $addedFeed = $feedService->mutate($operations)->getValue()[0];
    printf("Added GMB feed with ID %d\n", $addedFeed->getId());

    $customerFeedService =
        $adWordsServices->get($session, CustomerFeedService::class);

    // Add a CustomerFeed that associates the feed with this customer for
    // the LOCATION placeholder type.
    $customerFeed = new CustomerFeed();
    $customerFeed->setFeedId($addedFeed->getId());
    $customerFeed->setPlaceholderTypes([self::PLACEHOLDER_LOCATION]);

    // Create a matching function that will always evaluate to true.
    $customerMatchingFunction = new MatchingFunction();
    $constOperand = new ConstantOperand();
    $constOperand->setType(ConstantOperandConstantType::BOOLEAN);
    $constOperand->setBooleanValue(true);
    $customerMatchingFunction->setLhsOperand([$constOperand]);
    $customerMatchingFunction->setOperator(FunctionOperator::IDENTITY);
    $customerFeed->setMatchingFunction($customerMatchingFunction);

    // Create a customer feed operation and add it to the list.
    $operation = new CustomerFeedOperation();
    $operation->setOperand($customerFeed);
    $operation->setOperator(Operator::ADD);
    $operations = [$operation];

    // After the completion of the Feed ADD operation above the added feed will
    // not be available for usage in a CustomerFeed until the sync between the
    // AdWords and GMB accounts completes. The loop below will retry adding
    // the CustomerFeed up to ten times with an exponential back-off policy.
    $addedCustomerFeed = null;
    $numberOfAttempts = 0;
    do {
      $numberOfAttempts++;
      try {
        $addedCustomerFeed =
            $customerFeedService->mutate($operations)->getValue()[0];
        printf("Attempt #%d to add the CustomerFeed was successful\n",
            $numberOfAttempts);
      } catch (ApiException $e) {
        // Wait using exponential backoff policy
        $sleepSeconds = 5 * pow(2, $numberOfAttempts);
        printf(
            "Attempt #%d to add the CustomerFeed was not successful. "
                . "Waiting %d seconds before trying again.\n",
            $numberOfAttempts,
            $sleepSeconds
        );
        sleep($sleepSeconds);
      }
    } while ($numberOfAttempts < self::MAX_CUSTOMER_FEED_ADD_ATTEMPTS
        && $addedCustomerFeed === null);

    if ($addedCustomerFeed === null) {
      throw new Exception('Could not create the CustomerFeed after '
          . self::MAX_CUSTOMER_FEED_ADD_ATTEMPTS . ' attempts. Please retry '
          . 'the CustomerFeed ADD operation later.');
    }

    printf(
        "Added CustomerFeed for feed ID %d and placeholder type %d\n",
        $addedCustomerFeed->getFeedId(),
        $addedCustomerFeed->getPlaceholderTypes()[0]
    );

    // OPTIONAL: Create a CampaignFeed to specify which FeedItems to use at the
    // Campaign level.  This will be similar to the CampaignFeed in the
    // AddSitelinks example, except you can also filter based on the business
    // name and category of each FeedItem by using a FeedAttributeOperand in
    // your matching function.

    // OPTIONAL: Create an AdGroupFeed for even more fine grained control over
    // which feed items are used at the AdGroup level.
  }

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

    // If the GMB_EMAIL_ADDRESS is the same user you used to generate your
    // AdWords API refresh token, leave the assignment below unchanged.
    // Otherwise, to obtain an access token for your GMB account, run the
    // Auth/GetRefreshToken example. Make sure you are logged in as the same
    // user as GMB_EMAIL_ADDRESS above when you follow the link provided by the
    // example then call fetchAuthToken on the generated oAuth2 object and copy
    // and paste its 'access_token' value into the assignment below.
    $gmbAccessToken = $oAuth2Credential->fetchAuthToken()['access_token'];

    // 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::GMB_EMAIL_ADDRESS,
        $gmbAccessToken,
        (self::BUSINESS_ACCOUNT_IDENTIFIER === null) ? null
            : intval(self::BUSINESS_ACCOUNT_IDENTIFIER)
    );
  }
}

AddGoogleMyBusinessLocationExtensions::main();

Old

<?php
/**
 * This example adds a feed that syncs feed items from a Google
 * My Business (GMB) account and associates the feed with a customer.
 *
 * 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.
// The email address of either an owner or a manager of the GMB account.
define('GMB_EMAIL_ADDRESS', 'INSERT_GMB_EMAIL_ADDRESS');

// If the gmbEmailAddress above is for a GMB manager instead of the GMB account
// owner, then set businessAccountIdentifier to the +Page ID of a location for
// which the manager has access. See the location extensions guide at
// https://developers.google.com/adwords/api/docs/guides/feed-services-locations
// for details.
define('BUSINESS_ACCOUNT_IDENTIFIER', null);

// The placeholder type for location extensions.
// See the Placeholder reference page for a list of all the placeholder types
// and fields.
// https://developers.google.com/adwords/api/docs/appendix/placeholders
define('PLACEHOLDER_LOCATION', 7);

// The maximum number of CustomerFeed ADD operation attempts to make before
// throwing an exception.
define('MAX_CUSTOMER_FEED_ADD_ATTEMPTS', 10);

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $gmbEmailAddress E-Mail address of an owner or a manager of the
 *     GMB account
 * @param string $gmbAccessToken Access token for the GMB account
 */
function AddGoogleMyBusinessLocationExtensions(
    AdWordsUser $user, $gmbEmailAddress, $gmbAccessToken, $gmbBusinessAccount) {
  $feedService = $user->GetService('FeedService');

  // Create a feed that will sync to the Google My Business account specified
  // by gmbEmailAddress. Do not add FeedAttributes to this object, as AdWords
  // will add them automatically because this will be a system generated feed.
  $gmbFeed = new Feed();
  $gmbFeed->name = 'Google My Business feed #' . uniqid();

  $feedData = new PlacesLocationFeedData();
  $feedData->emailAddress = $gmbEmailAddress;
  $feedData->businessAccountIdentifier = $gmbBusinessAccount;

  // Optional: specify labels to filter Google My Business listings. If
  // specified, only listings that have any of the labels set are
  // synchronized into FeedItems.
  $feedData->labelFilters = array('Stores in New York City');

  $oAuthInfo = new OAuthInfo();
  $oAuthInfo->httpMethod = 'GET';
  $oAuthInfo->httpRequestUrl = 'https://www.googleapis.com/auth/adwords';
  $oAuthInfo->httpAuthorizationHeader = sprintf('Bearer %s', $gmbAccessToken);
  $feedData->oAuthInfo = $oAuthInfo;

  $gmbFeed->systemFeedGenerationData = $feedData;

  // Since this feed's feed items will be managed by AdWords,
  // you must set its origin to ADWORDS.
  $gmbFeed->origin = 'ADWORDS';

  // Create an operation to add the feed.
  $feedOperation = new FeedOperation();
  $feedOperation->operand = $gmbFeed;
  $feedOperation->operator = 'ADD';

  // Add the feed. Since it is a system generated feed, AdWords will
  // automatically:
  // 1. Set up the FeedAttributes on the feed.
  // 2. Set up a FeedMapping that associates the FeedAttributes of the feed
  // with the placeholder fields of the LOCATION placeholder type.
  $addFeedResult = $feedService->mutate(array($feedOperation));
  $addedFeed = $addFeedResult->value[0];
  printf("Added GMB feed with ID %d\n", $addedFeed->id);

  $customerFeedService = $user->GetService('CustomerFeedService');

  // Add a CustomerFeed that associates the feed with this customer for
  // the LOCATION placeholder type.
  $customerFeed = new CustomerFeed();
  $customerFeed->feedId = $addedFeed->id;
  $customerFeed->placeholderTypes = array(PLACEHOLDER_LOCATION);

  // Create a matching function that will always evaluate to true.
  $customerMatchingFunction = new FeedFunction();
  $constOperand = new ConstantOperand();
  $constOperand->type = 'BOOLEAN';
  $constOperand->booleanValue = true;
  $customerMatchingFunction->lhsOperand = array($constOperand);
  $customerMatchingFunction->operator = 'IDENTITY';
  $customerFeed->matchingFunction = $customerMatchingFunction;

  // Create an operation to add the customer feed.
  $customerFeedOperation = new CustomerFeedOperation();
  $customerFeedOperation->operand = $customerFeed;
  $customerFeedOperation->operator = 'ADD';

  // After the completion of the Feed ADD operation above the added feed will
  // not be available for usage in a CustomerFeed until the sync between the
  // AdWords and GMB accounts completes. The loop below will retry adding
  // the CustomerFeed up to ten times with an exponential back-off policy.
  $addedCustomerFeed = null;
  $numberOfAttempts = 0;
  do {
    $numberOfAttempts++;
    try {
      $customerFeedResult =
          $customerFeedService->mutate(array($customerFeedOperation));
      $addedCustomerFeed = $customerFeedResult->value[0];
      printf("Attempt #%d to add the CustomerFeed was successful\n",
          $numberOfAttempts);
    } catch (Exception $e) {
      // Wait using exponential backoff policy
      $sleepSeconds = 5 * pow(2, $numberOfAttempts);
      printf("Attempt #%d to add the CustomerFeed was not successful. "
          . "Waiting %d seconds before trying again.\n", $numberOfAttempts,
          $sleepSeconds);
      sleep($sleepSeconds);
    }
  } while ($numberOfAttempts < MAX_CUSTOMER_FEED_ADD_ATTEMPTS
      && $addedCustomerFeed == null);

  if($addedCustomerFeed == null) {
    throw new Exception('Could not create the CustomerFeed after '
       . MAX_CUSTOMER_FEED_ADD_ATTEMPTS . ' attempts. Please retry '
       . 'the CustomerFeed ADD operation later.');
  }

  printf("Added CustomerFeed for feed ID %d and placeholder type %d\n",
      $addedCustomerFeed->feedId, $addedCustomerFeed->placeholderTypes[0]);

  // OPTIONAL: Create a CampaignFeed to specify which FeedItems to use at the
  // Campaign level.  This will be similar to the CampaignFeed in the
  // AddSitelinks example, except you can also filter based on the business
  // name and category of each FeedItem by using a FeedAttributeOperand in
  // your matching function.

  // OPTIONAL: Create an AdGroupFeed for even more fine grained control over
  // which feed items are used at the AdGroup level.

}

// 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();

  $oAuth2Info = $user->GetOAuth2Info();
  $oAuth2Handler = $user->GetOAuth2Handler();
  if (!isset($oAuth2Info['access_token'])) {
    $oAuth2Info = $oAuth2Handler->GetOrRefreshAccessToken($oAuth2Info);
    $user->SetOAuth2Info($oAuth2Info);
  }

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

  // If the GMB_EMAIL_ADDRESS is the same user you used to generate your
  // AdWords API refresh token, leave the assignment below unchanged.
  // Otherwise, to obtain an access token for your GMB account, run the
  // Auth/GetRefreshToken example. Make sure you are logged in as the same user
  // as GMB_EMAIL_ADDRESS above when you follow the link provided by the example
  // then call GetOAuth2Info on the generated AdWordsUser object and copy and
  // paste the value into the assignment below.
  define('GMB_ACCESS_TOKEN', $oAuth2Info['access_token']);

  // Run the example.
  AddGoogleMyBusinessLocationExtensions(
      $user, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, BUSINESS_ACCOUNT_IDENTIFIER);

} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Add prices

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

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\CustomerExtensionSetting;
use Google\AdsApi\AdWords\v201705\cm\CustomerExtensionSettingOperation;
use Google\AdsApi\AdWords\v201705\cm\CustomerExtensionSettingService;
use Google\AdsApi\AdWords\v201705\cm\DayOfWeek;
use Google\AdsApi\AdWords\v201705\cm\ExtensionSetting;
use Google\AdsApi\AdWords\v201705\cm\FeedItemCampaignTargeting;
use Google\AdsApi\AdWords\v201705\cm\FeedItemScheduling;
use Google\AdsApi\AdWords\v201705\cm\FeedItemSchedule;
use Google\AdsApi\AdWords\v201705\cm\FeedType;
use Google\AdsApi\AdWords\v201705\cm\MinuteOfHour;
use Google\AdsApi\AdWords\v201705\cm\Money;
use Google\AdsApi\AdWords\v201705\cm\MoneyWithCurrency;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\cm\PriceFeedItem;
use Google\AdsApi\AdWords\v201705\cm\PriceExtensionType;
use Google\AdsApi\AdWords\v201705\cm\PriceExtensionPriceQualifier;
use Google\AdsApi\AdWords\v201705\cm\PriceExtensionPriceUnit;
use Google\AdsApi\AdWords\v201705\cm\PriceTableRow;
use Google\AdsApi\AdWords\v201705\cm\UrlList;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds a price extension and associates it with an account.
 * Campaign targeting is also set using the specified campaign ID.
 * To get campaigns, run GetCampaigns.php.
 */
class AddPrices {

  const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';
  const MICROS_PER_DOLLAR = 1000000;

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

    // Create the price extension feed item.
    $priceFeedItem = new PriceFeedItem();
    $priceFeedItem->setPriceExtensionType(PriceExtensionType::SERVICES);
    // Price qualifer is optional.
    $priceFeedItem->setPriceQualifier(PriceExtensionPriceQualifier::FROM);
    $priceFeedItem->setTrackingUrlTemplate(
        'http://tracker.example.com/?u={lpurl}');
    $priceFeedItem->setLanguage('en');
    $priceFeedItem->setCampaignTargeting(
        new FeedItemCampaignTargeting($campaignId));
    $priceFeedItem->setScheduling(new FeedItemScheduling([
        new FeedItemSchedule(DayOfWeek::SUNDAY, 10, MinuteOfHour::ZERO, 18,
            MinuteOfHour::ZERO),
        new FeedItemSchedule(DayOfWeek::SATURDAY, 10, MinuteOfHour::ZERO, 22,
            MinuteOfHour::ZERO)
    ]));

    // To create a price extension, at least three table rows are needed.
    $tableRows = [];
    $tableRows[] = self::createPriceTableRow(
        'Scrubs',
        'Body Scrub, Salt Scrub',
        'http://www.example.com/scrubs',
        60 * self::MICROS_PER_DOLLAR,
        'USD',
        PriceExtensionPriceUnit::PER_HOUR,
        'http://m.example.com/scrubs'
    );
    $tableRows[] = self::createPriceTableRow(
        'Hair Cuts',
        'Once a month',
        'http://www.example.com/haircuts',
        75 * self::MICROS_PER_DOLLAR,
        'USD',
        PriceExtensionPriceUnit::PER_MONTH,
        'http://m.example.com/haircuts'
    );
    $tableRows[] = self::createPriceTableRow(
        'Skin Care Package',
        'Four times a month',
        'http://www.example.com/skincarepackage',
        250 * self::MICROS_PER_DOLLAR,
        'USD',
        PriceExtensionPriceUnit::PER_MONTH
    );

    $priceFeedItem->setTableRows($tableRows);

    // Create your customer extension settings. This associates the price
    // extension to your account.
    $customerExtensionSetting = new CustomerExtensionSetting();
    $customerExtensionSetting->setExtensionType(FeedType::PRICE);
    $customerExtensionSetting->setExtensionSetting(new ExtensionSetting());
    $customerExtensionSetting->getExtensionSetting()->setExtensions(
        [$priceFeedItem]);

    // Create a customer extension setting operation and add it to the list.
    $operations = [];
    $operation = new CustomerExtensionSettingOperation();
    $operation->setOperator(Operator::ADD);
    $operation->setOperand($customerExtensionSetting);
    $operations = [$operation];

    // Add the price extension on the server.
    $result = $customerExtensionSettingService->mutate($operations);

    // Print out some information about the added extension setting.
    $newExtensionSetting = $result->getValue()[0];
    printf("Extension setting with type '%s' was added to your account.\n",
        $newExtensionSetting->getExtensionType());
  }

  /**
   * Creates a new price table row with the specified attributes.
   *
   * @param string $header the header of price table row
   * @param string $description the description of price table row
   * @param string $finalUrl the final URL of price table row
   * @param integer $priceInMicros the price in micro amount
   * @param string $currencyCode the 3-character currency code
   * @param string $priceUnit the unit of shown price
   * @param string|null $finalMobileUrl the mobile final URL of price table row
   */
  private static function createPriceTableRow(
      $header,
      $description,
      $finalUrl,
      $priceInMicros,
      $currencyCode,
      $priceUnit,
      $finalMobileUrl = null
  ) {
    $priceTableRow = new PriceTableRow();
    $priceTableRow->setHeader($header);
    $priceTableRow->setDescription($description);
    $priceTableRow->setFinalUrls(new UrlList([$finalUrl]));
    $money = new Money();
    $money->setMicroAmount($priceInMicros);
    $moneyWithCurrency = new MoneyWithCurrency();
    $moneyWithCurrency->setMoney($money);
    $moneyWithCurrency->setCurrencyCode($currencyCode);
    $priceTableRow->setPrice($moneyWithCurrency);
    $priceTableRow->setPriceUnit($priceUnit);

    if ($finalMobileUrl !== null) {
      $priceTableRow->setFinalMobileUrls(new UrlList([$finalMobileUrl]));
    }
    return $priceTableRow;
  }

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

AddPrices::main();

Old

<?php
/**
 * This example adds a price extension and associates it with an account.
 * Campaign targeting is also set using the specified campaign ID.
 * To get campaigns, run 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';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $campaignId the ID of campaign the price extension is
 *     targeted to
 */
function AddPricesExample(AdWordsUser $user, $campaignId) {
  // Get the services and load the required classes.
  $customerExtensionSettingService =
      $user->GetService('CustomerExtensionSettingService', ADWORDS_VERSION);

  // Create the price extension feed item.
  $priceFeedItem = new PriceFeedItem();
  $priceFeedItem->priceExtensionType = 'SERVICES';
  // Price qualifer is optional.
  $priceFeedItem->priceQualifier = 'FROM';
  $priceFeedItem->trackingUrlTemplate = 'http://tracker.example.com/?u={lpurl}';
  $priceFeedItem->language = 'en';
  $priceFeedItem->campaignTargeting =
      new FeedItemCampaignTargeting($campaignId);
  $priceFeedItem->scheduling = new FeedItemScheduling(array(
      new FeedItemSchedule('SUNDAY', 10, 'ZERO', 18, 'ZERO'),
      new FeedItemSchedule('SATURDAY', 10, 'ZERO', 22, 'ZERO')
  ));

  // To create a price extension, at least three table rows are needed.
  $tableRows = array();
  $tableRows[] = createPriceTableRow(
      'Scrubs',
      'Body Scrub, Salt Scrub',
      'http://www.example.com/scrubs',
      60 * AdWordsConstants::MICROS_PER_DOLLAR,
      'USD',
      'PER_HOUR'
  );
  $tableRows[] = createPriceTableRow(
      'Hair Cuts',
      'Once a month',
      'http://www.example.com/haircuts',
      75 * AdWordsConstants::MICROS_PER_DOLLAR,
      'USD',
      'PER_MONTH'
  );
  $tableRows[] = createPriceTableRow(
      'Skin Care Package',
      'Four times a month',
      'http://www.example.com/skincarepackage',
      250 * AdWordsConstants::MICROS_PER_DOLLAR,
      'USD',
      'PER_MONTH'
  );

  $priceFeedItem->tableRows = $tableRows;

  // Create your customer extension settings. This associates the price
  // extension to your account.
  $customerExtensionSetting = new CustomerExtensionSetting();
  $customerExtensionSetting->extensionType = 'PRICE';
  $customerExtensionSetting->extensionSetting = new ExtensionSetting();
  $customerExtensionSetting->extensionSetting->extensions =
      array($priceFeedItem);

  // Create operation.
  $operation = new CustomerExtensionSettingOperation();
  $operation->operator = 'ADD';
  $operation->operand = $customerExtensionSetting;

  $operations = array($operation);

  // Add the price extension.
  $result = $customerExtensionSettingService->mutate($operations);

  // Print the results.
  $newExtensionSetting = $result->value[0];
  printf("Extension setting with type '%s' was added to your account.\n",
      $newExtensionSetting->extensionType);
}

/**
 * Creates a new price table row with the specified attributes.
 *
 * @param string $header the header of price table row
 * @param string $description the description of price table row
 * @param string $finalUrl the final url of price table row
 * @param integer $priceInMicros the price in micro amount
 * @param string $currencyCode the 3-character currency code
 * @param string $priceUnit the unit of shown price
 */
function createPriceTableRow($header, $description, $finalUrl, $priceInMicros,
    $currencyCode, $priceUnit) {
  $priceTableRow = new PriceTableRow();
  $priceTableRow->header = $header;
  $priceTableRow->description = $description;
  $priceTableRow->finalUrls = new UrlList(array($finalUrl));
  $priceTableRow->price =
      new MoneyWithCurrency(new Money($priceInMicros), $currencyCode);
  $priceTableRow->priceUnit = $priceUnit;
  return $priceTableRow;
}

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

Add sitelinks 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\Extensions;

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\CampaignExtensionSetting;
use Google\AdsApi\AdWords\v201705\cm\CampaignExtensionSettingOperation;
use Google\AdsApi\AdWords\v201705\cm\CampaignExtensionSettingService;
use Google\AdsApi\AdWords\v201705\cm\ExtensionSetting;
use Google\AdsApi\AdWords\v201705\cm\FeedItemGeoRestriction;
use Google\AdsApi\AdWords\v201705\cm\FeedItemScheduling;
use Google\AdsApi\AdWords\v201705\cm\FeedItemSchedule;
use Google\AdsApi\AdWords\v201705\cm\FeedType;
use Google\AdsApi\AdWords\v201705\cm\GeoRestriction;
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\Operator;
use Google\AdsApi\AdWords\v201705\cm\SitelinkFeedItem;
use Google\AdsApi\AdWords\v201705\cm\UrlList;
use Google\AdsApi\AdWords\v201705\mcm\CustomerService;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds a sitelinks feed and associates it with a campaign.
 * To get campaigns, run BasicOperations/GetCampaigns.php.
 */
class AddSitelinks {

  const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session, $campaignId) {
    $campaignExtensionSettingService =
        $adWordsServices->get($session, CampaignExtensionSettingService::class);
    $customerService =
        $adWordsServices->get($session, CustomerService::class);

    // Find the matching customer and its time zone. The getCustomers method
    // will return a single Customer object corresponding to the user's
    // clientCustomerId.
    $customers = $customerService->getCustomers();
    $customer = $customers[0];
    printf("Found customer ID %d with time zone %s.\n",
        $customer->getCustomerId(), $customer->getDateTimeZone());

    $sitelinks = [];
    // Create a simple sitelink.
    $sitelink1 = new SitelinkFeedItem();
    $sitelink1->setSitelinkText('Store Hours');
    $sitelink1->setSitelinkFinalUrls(
        new UrlList(['http://www.example.com/storehours']));
    $sitelinks[] = $sitelink1;

    // This one to show the Thanksgiving specials link only from 20 - 27 Nov.
    $sitelink2 = new SitelinkFeedItem();
    $sitelink2->setSitelinkText('Thanksgiving Specials');
    $sitelink2->setSitelinkFinalUrls(
        new UrlList(['http://www.example.com/thanksgiving']));
    $sitelink2->setStartTime(
        date('Y') . '1120 000000 ' . $customer->getDateTimeZone());
    $sitelink2->setEndTime(
        date('Y') . '1127 235959 ' . $customer->getDateTimeZone());
    // Target this sitelink for United States only. See
    // https://developers.google.com/adwords/api/docs/appendix/geotargeting
    // for valid geolocation codes.
    $location = new Location();
    $location->setId(2840);
    $sitelink2->setGeoTargeting($location);

    // Restrict targeting only to people physically within the United States.
    // Otherwise, this could also show to people interested in the United States
    // but not physically located there.
    $sitelink2->setGeoTargetingRestriction(
        new FeedItemGeoRestriction(GeoRestriction::LOCATION_OF_PRESENCE));
    $sitelinks[] = $sitelink2;

    // Sitelink targetted on high end mobile.
    $sitelink3 = new SitelinkFeedItem();
    $sitelink3->setSitelinkText('Wifi available');
    $sitelink3->setSitelinkFinalUrls(
        new UrlList(['http://www.example.com/mobile/wifi']));
    $sitelink3->setDevicePreference(30001);
    // Target this sitelink only when the ad is triggered by the keyword
    // "free wifi".
    $keyword = new Keyword();
    $keyword->setText('free wifi');
    $keyword->setMatchType(KeywordMatchType::BROAD);
    $sitelink3->setKeywordTargeting($keyword);
    $sitelinks[] = $sitelink3;

    // Show the happy hours link only during Mon - Fri 6PM to 9PM.
    $sitelink4 = new SitelinkFeedItem();
    $sitelink4->setSitelinkText('Happy Hours Now!');
    $sitelink4->setSitelinkFinalUrls(
        new UrlList(['http://www.example.com/happyhours']));
    $sitelink4->setScheduling(new FeedItemScheduling([
        new FeedItemSchedule('MONDAY', 18, 'ZERO', 21, 'ZERO'),
        new FeedItemSchedule('TUESDAY', 18, 'ZERO', 21, 'ZERO'),
        new FeedItemSchedule('WEDNESDAY', 18, 'ZERO', 21, 'ZERO'),
        new FeedItemSchedule('THURSDAY', 18, 'ZERO', 21, 'ZERO'),
        new FeedItemSchedule('FRIDAY', 18, 'ZERO', 21, 'ZERO')
    ]));
    $sitelinks[] = $sitelink4;

    // Create your campaign extension settings. This associates the sitelinks
    // to your campaign.
    $campaignExtensionSetting = new CampaignExtensionSetting();
    $campaignExtensionSetting->setCampaignId($campaignId);
    $campaignExtensionSetting->setExtensionType(FeedType::SITELINK);
    $campaignExtensionSetting->setExtensionSetting(new ExtensionSetting());
    $campaignExtensionSetting->getExtensionSetting()->setExtensions($sitelinks);

    // Create a campaign extension setting operation and add it to the list.
    $operation = new CampaignExtensionSettingOperation();
    $operation->setOperator(Operator::ADD);
    $operation->setOperand($campaignExtensionSetting);
    $operations = [$operation];

    // Add the sitelinks on the server.
    $result = $campaignExtensionSettingService->mutate($operations);

    // Print out some information about the added extension setting.
    $newExtensionSetting = $result->getValue()[0];
    printf(
        "Extension setting with type '%s' was added to campaign ID %d\n",
        $newExtensionSetting->getExtensionType(),
        $newExtensionSetting->getCampaignId()
    );
  }

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

AddSitelinks::main();

Old

<?php
/**
 * This example adds a sitelinks feed and associates it with a campaign.
 * To get campaigns, run 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';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $campaignId the ID of the campaign to add the sitelinks to
 */
function AddSitelinksExample(AdWordsUser $user, $campaignId) {
  // Get the services and load the required classes.
  $campaignExtensionSettingService =
      $user->GetService('CampaignExtensionSettingService', ADWORDS_VERSION);
  $customerService = $user->GetService('CustomerService', ADWORDS_VERSION);

  // Find the matching customer and its time zone. The getCustomers method will
  // return a single Customer object corresponding to the user's
  // clientCustomerId.
  $customers = $customerService->getCustomers();
  $customer = $customers[0];
  printf("Found customer ID %d with time zone %s.\n", $customer->customerId,
      $customer->dateTimeZone);

  // Create the sitelinks:

  // A simple one.
  $sitelink1 = new SitelinkFeedItem();
  $sitelink1->sitelinkText = 'Store Hours';
  $sitelink1->sitelinkFinalUrls =
      new UrlList(array('http://www.example.com/storehours'));

  // This one to show the Thanksgiving specials link only from 20 - 27 Nov.
  $sitelink2 = new SitelinkFeedItem();
  $sitelink2->sitelinkText = 'Thanksgiving Specials';
  $sitelink2->sitelinkFinalUrls =
      new UrlList(array('http://www.example.com/thanksgiving'));
  $sitelink2->startTime = date('Y') . '1120 000000 ' . $customer->dateTimeZone;
  $sitelink2->endTime = date('Y') . '1127 235959 ' . $customer->dateTimeZone;
  // Target this sitelink for United States only. See
  // https://developers.google.com/adwords/api/docs/appendix/geotargeting
  // for valid geolocation codes.
  $location = new Location();
  $location->id = 2840;
  $sitelink2->geoTargeting = $location;

  // Restrict targeting only to people physically within the United States.
  // Otherwise, this could also show to people interested in the United States
  // but not physically located there.
  $sitelink2->geoTargetingRestriction =
      new FeedItemGeoRestriction('LOCATION_OF_PRESENCE');

  // Sitelink targetted on high end mobile.
  $sitelink3 = new SitelinkFeedItem();
  $sitelink3->sitelinkText = 'Wifi available';
  $sitelink3->sitelinkFinalUrls =
      new UrlList(array('http://www.example.com/mobile/wifi'));
  $sitelink3->devicePreference = 30001;
  // Target this sitelink only when the ad is triggered by the keyword
  // "free wifi".
  $keyword = new Keyword();
  $keyword->text = 'free wifi';
  $keyword->matchType = 'BROAD';
  $sitelink3->keywordTargeting = $keyword;

  // Show the happy hours link only during Mon - Fri 6PM to 9PM.
  $sitelink4 = new SitelinkFeedItem();
  $sitelink4->sitelinkText = 'Happy Hours Now!';
  $sitelink4->sitelinkFinalUrls =
      new UrlList(array('http://www.example.com/happyhours'));
  $sitelink4->scheduling = new FeedItemScheduling(array(
      new FeedItemSchedule('MONDAY', 18, 'ZERO', 21, 'ZERO'),
      new FeedItemSchedule('TUESDAY', 18, 'ZERO', 21, 'ZERO'),
      new FeedItemSchedule('WEDNESDAY', 18, 'ZERO', 21, 'ZERO'),
      new FeedItemSchedule('THURSDAY', 18, 'ZERO', 21, 'ZERO'),
      new FeedItemSchedule('FRIDAY', 18, 'ZERO', 21, 'ZERO')
  ));

  // Create your campaign extension settings. This associates the sitelinks
  // to your campaign.
  $campaignExtensionSetting = new CampaignExtensionSetting();
  $campaignExtensionSetting->campaignId = $campaignId;
  $campaignExtensionSetting->extensionType = 'SITELINK';
  $campaignExtensionSetting->extensionSetting = new ExtensionSetting();
  $campaignExtensionSetting->extensionSetting->extensions = array();
  $campaignExtensionSetting->extensionSetting->extensions[] = $sitelink1;
  $campaignExtensionSetting->extensionSetting->extensions[] = $sitelink2;
  $campaignExtensionSetting->extensionSetting->extensions[] = $sitelink3;
  $campaignExtensionSetting->extensionSetting->extensions[] = $sitelink4;

  // Create operation.
  $operation = new CampaignExtensionSettingOperation();
  $operation->operator = 'ADD';
  $operation->operand = $campaignExtensionSetting;

  $operations = array($operation);

  // Add the sitelinks.
  $result = $campaignExtensionSettingService->mutate($operations);

  // Print the results.
  $newExtensionSetting = $result->value[0];
  printf("Extension setting with type '%s' was added to campaign ID %d\n",
      $newExtensionSetting->extensionType, $newExtensionSetting->campaignId);

  return $newExtensionSetting;
}

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

Add sitelinks to a campaign using feeds

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

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\AttributeFieldMapping;
use Google\AdsApi\AdWords\v201705\cm\CampaignFeed;
use Google\AdsApi\AdWords\v201705\cm\CampaignFeedOperation;
use Google\AdsApi\AdWords\v201705\cm\CampaignFeedService;
use Google\AdsApi\AdWords\v201705\cm\Feed;
use Google\AdsApi\AdWords\v201705\cm\FeedAttribute;
use Google\AdsApi\AdWords\v201705\cm\FeedAttributeType;
use Google\AdsApi\AdWords\v201705\cm\FeedItem;
use Google\AdsApi\AdWords\v201705\cm\FeedItemAttributeValue;
use Google\AdsApi\AdWords\v201705\cm\FeedItemGeoRestriction;
use Google\AdsApi\AdWords\v201705\cm\FeedItemOperation;
use Google\AdsApi\AdWords\v201705\cm\FeedItemService;
use Google\AdsApi\AdWords\v201705\cm\FeedMapping;
use Google\AdsApi\AdWords\v201705\cm\FeedMappingOperation;
use Google\AdsApi\AdWords\v201705\cm\FeedMappingService;
use Google\AdsApi\AdWords\v201705\cm\FeedOperation;
use Google\AdsApi\AdWords\v201705\cm\FeedOrigin;
use Google\AdsApi\AdWords\v201705\cm\FeedService;
use Google\AdsApi\AdWords\v201705\cm\GeoRestriction;
use Google\AdsApi\AdWords\v201705\cm\Location;
use Google\AdsApi\AdWords\v201705\cm\MatchingFunction;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds a sitelinks feed and associates it with a campaign.
 * To get campaigns, run GetCampaigns.php.
 */
class AddSitelinksUsingFeeds {

  const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';

  // See the Placeholder reference page for a list of all the placeholder types
  // and fields.
  // https://developers.google.com/adwords/api/docs/appendix/placeholders.html
  const PLACEHOLDER_SITELINKS = 1;
  const PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = 1;
  const PLACEHOLDER_FIELD_SITELINK_FINAL_URL = 5;
  const PLACEHOLDER_FIELD_LINE_2_TEXT = 3;
  const PLACEHOLDER_FIELD_LINE_3_TEXT = 4;

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session, $campaignId) {
    $sitelinksData = self::createSitelinksFeed($adWordsServices, $session);
    $sitelinksData = self::createSitelinksFeedItems($adWordsServices, $session,
        $sitelinksData);
    self::createSitelinksFeedMapping(
        $adWordsServices, $session, $sitelinksData);
    self::createSitelinksCampaignFeed(
        $adWordsServices, $session, $sitelinksData, $campaignId);
  }

  /**
   * Creates the feed that holds the sitelinks data.
   */
  private static function createSitelinksFeed(AdWordsServices $adWordsServices,
      AdWordsSession $session) {
    $feedService = $adWordsServices->get($session, FeedService::class);

    // Holds the IDs associated to the feeds metadata.
    $sitelinksData = [];

    // Create feed attributes.
    $textAttribute = new FeedAttribute();
    $textAttribute->setType(FeedAttributeType::STRING);
    $textAttribute->setName('Link Text');
    $finalUrlAttribute = new FeedAttribute();
    $finalUrlAttribute->setType(FeedAttributeType::URL_LIST);
    $finalUrlAttribute->setName('Link URL');
    $line2Attribute = new FeedAttribute();
    $line2Attribute->setType(FeedAttributeType::STRING);
    $line2Attribute->setName('Line 2');
    $line3Attribute = new FeedAttribute();
    $line3Attribute->setType(FeedAttributeType::STRING);
    $line3Attribute->setName('Line 3');

    // Create the feed.
    $sitelinksFeed = new Feed();
    $sitelinksFeed->setName('Feed For Sitelinks #' . uniqid());
    $sitelinksFeed->setAttributes(
        [$textAttribute, $finalUrlAttribute, $line2Attribute, $line3Attribute]);
    $sitelinksFeed->setOrigin(FeedOrigin::USER);

    // Create the feed operation and add it on the server.
    $operation = new FeedOperation();
    $operation->setOperator(Operator::ADD);
    $operation->setOperand($sitelinksFeed);
    $result = $feedService->mutate([$operation]);

    // Print out some information about the created feed.
    $savedFeed = $result->getValue()[0];
    $sitelinksData['sitelinksFeedId'] = $savedFeed->getId();
    $savedAttributes = $savedFeed->getAttributes();
    $sitelinksData['linkTextFeedAttributeId'] = $savedAttributes[0]->getId();
    $sitelinksData['linkFinalUrlFeedAttributeId'] =
        $savedAttributes[1]->getId();
    $sitelinksData['line2FeedAttribute'] = $savedAttributes[2]->getId();
    $sitelinksData['line3FeedAttribute'] = $savedAttributes[3]->getId();

    printf(
        "Feed with name '%s', ID %d with linkTextAttributeId %d, "
        . "linkFinalUrlAttributeId %d, line2AttributeId %d and "
        . "line3AttributeId %d was created.\n",
        $savedFeed->getName(),
        $savedFeed->getId(),
        $savedAttributes[0]->getId(),
        $savedAttributes[1]->getId(),
        $savedAttributes[2]->getId(),
        $savedAttributes[3]->getId()
    );

    return $sitelinksData;
  }

  /**
   * Creates sitelinks feed items and add it to the feed.
   */
  private static function createSitelinksFeedItems(
      AdWordsServices $adWordsServices,
      AdWordsSession $session,
      array $sitelinksData
  ) {
    $feedItemService = $adWordsServices->get($session, FeedItemService::class);

    // Create operations to add feed items.
    $home = self::newSitelinkFeedItemAddOperation(
        $sitelinksData,
        'Home',
        'http://www.example.com',
        'Home line 2',
        'Home line 3'
    );
    $stores = self::newSitelinkFeedItemAddOperation(
        $sitelinksData,
        'Stores',
        'http://www.example.com/stores',
        'Stores line 2',
        'Stores line 3'
    );
    $onSale = self::newSitelinkFeedItemAddOperation(
        $sitelinksData,
        'On Sale',
        'http://www.example.com/sale',
        'On Sale line 2',
        'On Sale line 3'
    );
    $support = self::newSitelinkFeedItemAddOperation(
        $sitelinksData,
        'Support',
        'http://www.example.com/support',
        'Support line 2',
        'Support line 3'
    );
    $products = self::newSitelinkFeedItemAddOperation(
        $sitelinksData,
        'Products',
        'http://www.example.com/products',
        'Products line 2',
        'Products line 3'
    );
    // This site link is using geographical targeting by specifying the
    // criterion ID for California.
    $aboutUs = self::newSitelinkFeedItemAddOperation(
        $sitelinksData,
        'About Us',
        'http://www.example.com/about',
        'About Us line 2',
        'About Us line 3',
        21137
    );

    // Add feed item operations on the server and print out some information.
    $result = $feedItemService->mutate(
        [$home, $stores, $onSale, $support, $products, $aboutUs]);
    $sitelinksData['sitelinkFeedItemIds'] = [];

    foreach ($result->getValue() as $feedItem) {
      printf("Feed item with feed item ID %d was added.\n",
          $feedItem->getFeedItemId());
      $sitelinksData['sitelinkFeedItemIds'][] = $feedItem->getFeedItemId();
    }

    return $sitelinksData;
  }

  /**
   * Maps the feed attributes to the sitelink placeholders.
   */
  private static function createSitelinksFeedMapping(
      AdWordsServices $adWordsServices,
      AdWordsSession $session,
      array $sitelinksData
  ) {
    $feedMappingService =
        $adWordsServices->get($session, FeedMappingService::class);

    // Map the feed attribute IDs to the field ID constants.
    $linkTextFieldMapping = new AttributeFieldMapping();
    $linkTextFieldMapping->setFeedAttributeId(
        $sitelinksData['linkTextFeedAttributeId']);
    $linkTextFieldMapping->setFieldId(
        self::PLACEHOLDER_FIELD_SITELINK_LINK_TEXT);
    $linkFinalUrlFieldMapping = new AttributeFieldMapping();
    $linkFinalUrlFieldMapping->setFeedAttributeId(
        $sitelinksData['linkFinalUrlFeedAttributeId']);
    $linkFinalUrlFieldMapping->setFieldId(
        self::PLACEHOLDER_FIELD_SITELINK_FINAL_URL);
    $line2FieldMapping = new AttributeFieldMapping();
    $line2FieldMapping->setFeedAttributeId(
        $sitelinksData['line2FeedAttribute']);
    $line2FieldMapping->setFieldId(self::PLACEHOLDER_FIELD_LINE_2_TEXT);
    $line3FieldMapping = new AttributeFieldMapping();
    $line3FieldMapping->setFeedAttributeId(
        $sitelinksData['line3FeedAttribute']);
    $line3FieldMapping->setFieldId(self::PLACEHOLDER_FIELD_LINE_3_TEXT);

    // Create the feed mapping and feed mapping operation.
    $feedMapping = new FeedMapping();
    $feedMapping->setPlaceholderType(self::PLACEHOLDER_SITELINKS);
    $feedMapping->setFeedId($sitelinksData['sitelinksFeedId']);
    $feedMapping->setAttributeFieldMappings([$linkTextFieldMapping,
        $linkFinalUrlFieldMapping, $line2FieldMapping, $line3FieldMapping]);

    $operation = new FeedMappingOperation();
    $operation->setOperand($feedMapping);
    $operation->setOperator(Operator::ADD);

    // Create the feed mapping operation on the server and print out some
    // information.
    $result = $feedMappingService->mutate([$operation]);
    foreach ($result->getValue() as $feedMapping) {
      printf(
          "Feed mapping with ID %d and placeholder type %d was saved for "
              .  "feed with ID %d.\n",
          $feedMapping->getFeedMappingId(),
          $feedMapping->getPlaceholderType(),
          $feedMapping->getFeedId()
      );
    }
  }

  /**
   * Creates the campaign feed associated to the populated feed data for the
   * specified campaign ID.
   */
  private static function createSitelinksCampaignFeed(
      AdWordsServices $adWordsServices,
      AdWordsSession $session,
      array $sitelinksData,
      $campaignId
  ) {
    $campaignFeedService =
        $adWordsServices->get($session, CampaignFeedService::class);
    $matchingFunctionString = sprintf(
        'AND( IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, "Mobile") )',
        implode(',', $sitelinksData['sitelinkFeedItemIds'])
    );

    // Create a campaign feed and its feed function.
    $campaignFeed = new CampaignFeed();
    $campaignFeed->setFeedId($sitelinksData['sitelinksFeedId']);
    $campaignFeed->setCampaignId($campaignId);

    $matchingFunction = new MatchingFunction();
    $matchingFunction->setFunctionString($matchingFunctionString);
    $campaignFeed->setMatchingFunction($matchingFunction);
    $campaignFeed->setPlaceholderTypes([self::PLACEHOLDER_SITELINKS]);

    // Create the campaign feed operation.
    $operation = new CampaignFeedOperation();
    $operation->setOperand($campaignFeed);
    $operation->setOperator(Operator::ADD);

    // Create the campaign feed on the server and print out some information.
    $result = $campaignFeedService->mutate([$operation]);
    foreach ($result->getValue() as $savedCampaignFeed) {
      printf(
          "Campaign with ID %d was associated with feed with ID %d.\n",
          $savedCampaignFeed->getCampaignId(),
          $savedCampaignFeed->getFeedId()
      );
    }
  }

  /**
   * Creates a site link feed item and wraps it in an ADD operation.
   *
   * @param array $sitelinksData IDs associated to created sitelinks feed
   *     metadata
   * @param string $text the text of the sitelink
   * @param string $finalUrl the final URL of the sitelink
   * @param string $line2 the first line of the sitelink description
   * @param string $line3 the second line of the sitelink description
   * @param int|null $locationId the criterion ID of location to be targeted
   */
  private static function newSitelinkFeedItemAddOperation(
      array $sitelinksData,
      $text,
      $finalUrl,
      $line2,
      $line3,
      $locationId = null
  ) {
    // Create the feed item attribute values for our text values.
    $linkTextAttributeValue = new FeedItemAttributeValue();
    $linkTextAttributeValue->setFeedAttributeId(
        $sitelinksData['linkTextFeedAttributeId']);
    $linkTextAttributeValue->setStringValue($text);
    $linkFinalUrlAttributeValue = new FeedItemAttributeValue();
    $linkFinalUrlAttributeValue->setFeedAttributeId(
        $sitelinksData['linkFinalUrlFeedAttributeId']);
    $linkFinalUrlAttributeValue->setStringValues([$finalUrl]);
    $line2AttributeValue = new FeedItemAttributeValue();
    $line2AttributeValue->setFeedAttributeId(
        $sitelinksData['line2FeedAttribute']);
    $line2AttributeValue->setStringValue($line2);
    $line3AttributeValue = new FeedItemAttributeValue();
    $line3AttributeValue->setFeedAttributeId(
        $sitelinksData['line3FeedAttribute']);
    $line3AttributeValue->setStringValue($line3);

    // Create the feed item.
    $item = new FeedItem();
    $item->setFeedId($sitelinksData['sitelinksFeedId']);
    $item->setAttributeValues([
        $linkTextAttributeValue,
        $linkFinalUrlAttributeValue,
        $line2AttributeValue,
        $line3AttributeValue
    ]);

    // OPTIONAL: Use geographical targeting on a feed.
    // The IDs can be found in the documentation or retrieved with the
    // LocationCriterionService.
    if ($locationId !== null) {
      $location = new Location();
      $location->setId($locationId);
      $item->setGeoTargeting($location);
      $item->setGeoTargetingRestriction(
          new FeedItemGeoRestriction(GeoRestriction::LOCATION_OF_PRESENCE));
    }

    // Create the feed item operation.
    $operation = new FeedItemOperation();
    $operation->setOperand($item);
    $operation->setOperator(Operator::ADD);

    return $operation;
  }

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

AddSitelinksUsingFeeds::main();

Old

<?php
/**
 * This example adds a sitelinks feed and associates it with a campaign.
 * To get campaigns, run 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';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $campaignId the ID of the campaign to add the sitelinks to
 */
function AddSitelinksUsingFeedsExample(AdWordsUser $user, $campaignId) {
  $sitelinksData = CreateSitelinksFeed($user);
  $sitelinksData = CreateSitelinksFeedItems($user, $sitelinksData);
  CreateSitelinksFeedMapping($user, $sitelinksData);
  CreateSitelinksCampaignFeed($user, $sitelinksData, $campaignId);
}

/**
 * Creates the feed that holds the sitelinks data.
 * @param AdWordsUser $user the user to run the example with
 */
function CreateSitelinksFeed(AdWordsUser $user) {
  // Map that holds IDs associated to the feeds metadata.
  $sitelinksData = array();

  // Get the FeedService, which loads the required classes.
  $feedService = $user->GetService('FeedService', ADWORDS_VERSION);

  // Create attributes.
  $textAttribute = new FeedAttribute();
  $textAttribute->type = 'STRING';
  $textAttribute->name = 'Link Text';
  $finalUrlAttribute = new FeedAttribute();
  $finalUrlAttribute->type = 'URL_LIST';
  $finalUrlAttribute->name = 'Link URL';
  $line1Attribute = new FeedAttribute();
  $line1Attribute->type = 'STRING';
  $line1Attribute->name = 'Line 1 Description';
  $line2Attribute = new FeedAttribute();
  $line2Attribute->type = 'STRING';
  $line2Attribute->name = 'Line 2 Description';

  // Create the feed.
  $sitelinksFeed = new Feed();
  $sitelinksFeed->name = 'Feed For Sitelinks';
  $sitelinksFeed->attributes = array($textAttribute, $finalUrlAttribute,
      $line1Attribute, $line2Attribute);
  $sitelinksFeed->origin = 'USER';

  // Create operation.
  $operation = new FeedOperation();
  $operation->operator = 'ADD';
  $operation->operand = $sitelinksFeed;

  $operations = array($operation);

  // Add the feed.
  $result = $feedService->mutate($operations);

  $savedFeed = $result->value[0];
  $sitelinksData['sitelinksFeedId'] = $savedFeed->id;
  $savedAttributes = $savedFeed->attributes;
  $sitelinksData['linkTextFeedAttributeId'] = $savedAttributes[0]->id;
  $sitelinksData['linkFinalUrlFeedAttributeId'] = $savedAttributes[1]->id;
  $sitelinksData['line1FeedAttribute'] = $savedAttributes[2]->id;
  $sitelinksData['line2FeedAttribute'] = $savedAttributes[3]->id;

  printf('Feed with name "%s" and ID %d with linkTextAttributeId %d'
      . ", linkFinalUrlAttributeId %d, line1Attribute %d and line2Attribute %d "
      . "were created.\n",
      $savedFeed->name,
      $savedFeed->id,
      $savedAttributes[0]->id,
      $savedAttributes[1]->id,
      $savedAttributes[2]->id,
      $savedAttributes[3]->id);

  return $sitelinksData;
}

/**
 * Adds sitelinks items to the feed.
 * @param AdWordsUser $user the user to run the example with
 * @param array $sitelinksData IDs associated to created sitelinks feed metadata
 */
function CreateSitelinksFeedItems(AdWordsUser $user, $sitelinksData) {
  // Get the FeedItemService, which loads the required classes.
  $feedItemService = $user->GetService('FeedItemService', ADWORDS_VERSION);

  // Create operations to add FeedItems.
  $home = NewSitelinkFeedItemAddOperation($sitelinksData, 'Home',
      'http://www.example.com', 'Home line 1', 'Home line 2');
  $stores = NewSitelinkFeedItemAddOperation($sitelinksData, 'Stores',
      'http://www.example.com/stores', 'Stores line 1', 'Stores line 2');
  $onSale = NewSitelinkFeedItemAddOperation($sitelinksData, 'On Sale',
      'http://www.example.com/sale', 'On Sale line 1', 'On Sale line 2');
  $support = NewSitelinkFeedItemAddOperation($sitelinksData, 'Support',
      'http://www.example.com/support', 'Support line 1', 'Support line 2');
  $products = NewSitelinkFeedItemAddOperation($sitelinksData, 'Products',
      'http://www.example.com/products', 'Products line 1', 'Products line 2');
  // This site link is using geographical targeting by specifying the criterion
  // ID for California.
  $aboutUs = NewSitelinkFeedItemAddOperation($sitelinksData, 'About Us',
      'http://www.example.com/about', 'About Us line 1', 'About Us line 2',
      21137);

  $operations = array($home, $stores, $onSale, $support, $products, $aboutUs);

  $result = $feedItemService->mutate($operations);
  $sitelinksData['sitelinkFeedItemIds'] = array();

  foreach ($result->value as $feedItem) {
    printf("FeedItem with feedItemId %d was added.\n", $feedItem->feedItemId);
    $sitelinksData['sitelinkFeedItemIds'][] = $feedItem->feedItemId;
  }

  return $sitelinksData;
}

// See the Placeholder reference page for a list of all the placeholder types
// and fields.
// https://developers.google.com/adwords/api/docs/appendix/placeholders.html
define('PLACEHOLDER_SITELINKS', 1);
define('PLACEHOLDER_FIELD_SITELINK_LINK_TEXT', 1);
define('PLACEHOLDER_FIELD_SITELINK_FINAL_URL', 5);
define('PLACEHOLDER_FIELD_LINE_1_TEXT', 3);
define('PLACEHOLDER_FIELD_LINE_2_TEXT', 4);

/**
 * Maps the feed attributes to the sitelink placeholders.
 * @param AdWordsUser $user the user to run the example with
 * @param array $sitelinksData IDs associated to created sitelinks feed metadata
 */
function CreateSitelinksFeedMapping(AdWordsUser $user, $sitelinksData) {
  // Get the FeedMappingService, which loads the required classes.
  $feedMappingService = $user->GetService('FeedMappingService',
      ADWORDS_VERSION);

  // Map the FeedAttributeIds to the fieldId constants.
  $linkTextFieldMapping = new AttributeFieldMapping();
  $linkTextFieldMapping->feedAttributeId =
      $sitelinksData['linkTextFeedAttributeId'];
  $linkTextFieldMapping->fieldId = PLACEHOLDER_FIELD_SITELINK_LINK_TEXT;
  $linkFinalUrlFieldMapping = new AttributeFieldMapping();
  $linkFinalUrlFieldMapping->feedAttributeId =
      $sitelinksData['linkFinalUrlFeedAttributeId'];
  $linkFinalUrlFieldMapping->fieldId = PLACEHOLDER_FIELD_SITELINK_FINAL_URL;
  $line1FieldMapping = new AttributeFieldMapping();
  $line1FieldMapping->feedAttributeId = $sitelinksData['line1FeedAttribute'];
  $line1FieldMapping->fieldId = PLACEHOLDER_FIELD_LINE_1_TEXT;
  $line2FieldMapping = new AttributeFieldMapping();
  $line2FieldMapping->feedAttributeId = $sitelinksData['line2FeedAttribute'];
  $line2FieldMapping->fieldId = PLACEHOLDER_FIELD_LINE_2_TEXT;

  // Create the FieldMapping and operation.
  $feedMapping = new FeedMapping();
  $feedMapping->placeholderType = PLACEHOLDER_SITELINKS;
  $feedMapping->feedId = $sitelinksData['sitelinksFeedId'];
  $feedMapping->attributeFieldMappings =
      array($linkTextFieldMapping, $linkFinalUrlFieldMapping,
          $line1FieldMapping, $line2FieldMapping);
  $operation = new FeedMappingOperation();
  $operation->operand = $feedMapping;
  $operation->operator = 'ADD';

  $operations = array($operation);

  // Save the field mapping.
  $result = $feedMappingService->mutate($operations);
  foreach ($result->value as $feedMapping) {
    printf('Feed mapping with ID %d and placeholderType %d was saved for ' .
        "feed with ID %d.\n",
        $feedMapping->feedMappingId,
        $feedMapping->placeholderType,
        $feedMapping->feedId);
  }
}

/**
 * Creates the CampaignFeed associated to the feed data already populated.
 * @param AdWordsUser $user the user to run the example with
 * @param array $sitelinksData IDs associated to created sitelinks feed metadata
 * @param string $campaignId the ID of the campaign to add the sitelinks to
 */
function CreateSitelinksCampaignFeed(AdWordsUser $user, $sitelinksData,
    $campaignId) {
  // Get the CampaignFeedService, which loads the required classes.
  $campaignFeedService = $user->GetService('CampaignFeedService',
      ADWORDS_VERSION);
  $matchingFunctionString = sprintf(
      'AND( IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, "Mobile") )',
      implode(',', $sitelinksData['sitelinkFeedItemIds']));

  $campaignFeed = new CampaignFeed();
  $campaignFeed->feedId = $sitelinksData['sitelinksFeedId'];
  $campaignFeed->campaignId = $campaignId;

  $matchingFunction = new FeedFunction();
  $matchingFunction->functionString = $matchingFunctionString;
  $campaignFeed->matchingFunction = $matchingFunction;
  // Specifying placeholder types on the CampaignFeed allows the same feed
  // to be used for different placeholders in different Campaigns.
  $campaignFeed->placeholderTypes = array(PLACEHOLDER_SITELINKS);

  $operation = new CampaignFeedOperation();
  $operation->operand = $campaignFeed;
  $operation->operator = 'ADD';

  $operations = array($operation);

  $result = $campaignFeedService->mutate($operations);
  foreach ($result->value as $savedCampaignFeed) {
    printf("Campaign with ID %d was associated with feed with ID %d.\n",
        $savedCampaignFeed->campaignId,
        $savedCampaignFeed->feedId);
  }
}

/**
 * Creates a SitelinkFeedItem and wraps it in an ADD operation.
 * @param array $sitelinksData IDs associated to created sitelinks feed metadata
 * @param string $text text of the sitelink
 * @param string $finalUrl URL of the sitelink
 * @param string $line1 first line of the sitelink description
 * @param string $line2 second line of the sitelink description
 * @param int $locationId the criterion ID of location to be targeted
 */
function NewSitelinkFeedItemAddOperation($sitelinksData, $text, $finalUrl,
    $line1, $line2, $locationId = null) {
  // Create the FeedItemAttributeValues for our text values.
  $linkTextAttributeValue = new FeedItemAttributeValue();
  $linkTextAttributeValue->feedAttributeId =
      $sitelinksData['linkTextFeedAttributeId'];
  $linkTextAttributeValue->stringValue = $text;
  $linkFinalUrlAttributeValue = new FeedItemAttributeValue();
  $linkFinalUrlAttributeValue->feedAttributeId =
      $sitelinksData['linkFinalUrlFeedAttributeId'];
  $linkFinalUrlAttributeValue->stringValues = array($finalUrl);
  $line1AttributeValue = new FeedItemAttributeValue();
  $line1AttributeValue->feedAttributeId = $sitelinksData['line1FeedAttribute'];
  $line1AttributeValue->stringValue = $line1;
  $line2AttributeValue = new FeedItemAttributeValue();
  $line2AttributeValue->feedAttributeId = $sitelinksData['line2FeedAttribute'];
  $line2AttributeValue->stringValue = $line2;

  // Create the feed item and operation.
  $item = new FeedItem();
  $item->feedId = $sitelinksData['sitelinksFeedId'];
  $item->attributeValues =
      array($linkTextAttributeValue, $linkFinalUrlAttributeValue,
          $line1AttributeValue, $line2AttributeValue);

  // OPTIONAL: Use geographical targeting on a feed.
  // The IDs can be found in the documentation or retrieved with the
  // LocationCriterionService.
  if ($locationId !== null) {
    $location = new Location();
    $location->id = $locationId;
    $item->geoTargeting = $location;
    $item->geoTargetingRestriction =
        new FeedItemGeoRestriction('LOCATION_OF_PRESENCE');
  }

  $operation = new FeedItemOperation();
  $operation->operand = $item;
  $operation->operator = 'ADD';
  return $operation;
}

// 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.
  AddSitelinksUsingFeedsExample($user, $campaignId);
} 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.