Miscellaneous Samples

The code samples below provide examples of miscellaneous management functions available in the AdWords API. Client Library.

Get all videos and images

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

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\MediaMediaType;
use Google\AdsApi\AdWords\v201705\cm\MediaService;
use Google\AdsApi\AdWords\v201705\cm\OrderBy;
use Google\AdsApi\AdWords\v201705\cm\Paging;
use Google\AdsApi\AdWords\v201705\cm\Predicate;
use Google\AdsApi\AdWords\v201705\cm\PredicateOperator;
use Google\AdsApi\AdWords\v201705\cm\Selector;
use Google\AdsApi\AdWords\v201705\cm\SortOrder;
use Google\AdsApi\Common\OAuth2TokenBuilder;
use Google\AdsApi\Common\Util\MapEntries;

/**
 * This example gets all images and videos. To upload an image, run
 * UploadImage.php. To upload a video, see http://goo.gl/Uqn0l.
 */
class GetAllImagesAndVideos {

  const PAGE_LIMIT = 500;

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

    // Create selector.
    $selector = new Selector();
    $selector->setFields(['MediaId', 'Width', 'Height', 'MimeType', 'Name']);
    $selector->setOrdering([new OrderBy('MediaId', SortOrder::ASCENDING)]);
    $selector->setPredicates([new Predicate('Type', PredicateOperator::IN,
        [MediaMediaType::IMAGE, MediaMediaType::VIDEO])]);
    $selector->setPaging(new Paging(0, self::PAGE_LIMIT));

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

      // Display results.
      if ($page->getEntries() !== null) {
        $totalNumEntries = $page->getTotalNumEntries();
        foreach ($page->getEntries() as $media) {
          if ($media->getType() === MediaMediaType::IMAGE) {
            $dimensions =
                MapEntries::toAssociativeArray($media->getDimensions());
            printf(
                "Image with dimensions %dx%d, MIME type '%s', and ID %d "
                    . "was found.\n",
                $dimensions['FULL']->getWidth(),
                $dimensions['FULL']->getHeight(),
                $media->getMimeType(),
                $media->getMediaId()
            );
          } else if ($media->getType() === MediaMediaType::VIDEO) {
            printf("Video with name '%s' and ID %d was found.\n",
                $media->getName(), $media->getMediaId());
          }
        }
      }

      // Advance the paging index.
      $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);
  }
}

GetAllImagesAndVideos::main();

Old

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

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

require_once UTIL_PATH . '/MediaUtils.php';
require_once UTIL_PATH . '/MapUtils.php';

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

  // Create selector.
  $selector = new Selector();
  $selector->fields = array('MediaId', 'Width', 'Height', 'MimeType', 'Name');
  $selector->ordering = array(new OrderBy('MediaId', 'ASCENDING'));

  // Create predicates.
  $selector->predicates[] =
      new Predicate('Type', 'IN', array('IMAGE', 'VIDEO'));

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

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

    // Display images.
    if (isset($page->entries)) {
      foreach ($page->entries as $media) {
        if ($media->MediaType == 'Image') {
          $dimensions = MapUtils::GetMap($media->dimensions);
          printf("Image with dimensions '%dx%d', MIME type '%s', and id '%s' "
              . "was found.\n", $dimensions['FULL']->width,
              $dimensions['FULL']->height, $media->mimeType, $media->mediaId);
        } else if ($media->MediaType == 'Video') {
          printf("Video with name '%s' and id '%s' was found.\n", $media->name,
              $media->mediaId);
        }
      }
    } else {
      print "No images or videos 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.
  GetAllImagesAndVideosExample($user);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Upload an image

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

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\Image;
use Google\AdsApi\AdWords\v201705\cm\MediaMediaType;
use Google\AdsApi\AdWords\v201705\cm\MediaService;
use Google\AdsApi\Common\OAuth2TokenBuilder;
use Google\AdsApi\Common\Util\MapEntries;

/**
 * This example uploads an image.
 */
class UploadImage {

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

    // Create an image and add it to the images list.
    $image = new Image();
    $image->setData(file_get_contents('http://goo.gl/HJM3L'));
    $image->setType(MediaMediaType::IMAGE);
    $images = [$image];

    // Upload the image to the server.
    $result = $mediaService->upload($images);

    // Print out some information about the uploaded image.
    $image = $result[0];
    $dimensions = MapEntries::toAssociativeArray($image->getDimensions());
    printf(
        "Image with dimensions '%dx%d', MIME type '%s', and id %d was "
            . "uploaded.\n",
        $dimensions['FULL']->getWidth(),
        $dimensions['FULL']->getHeight(),
        $image->getMimeType(),
        $image->getMediaId()
    );
  }

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

UploadImage::main();

Old

<?php
/**
 * This example uploads an image. To get images, run GetAllImagesAndVideos.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';

require_once UTIL_PATH . '/MediaUtils.php';
require_once UTIL_PATH . '/MapUtils.php';

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

  // Create image.
  $image = new Image();
  $image->data = MediaUtils::GetBase64Data('http://goo.gl/HJM3L');
  $image->type = 'IMAGE';

  // Make the upload request.
  $result = $mediaService->upload(array($image));

  // Display result.
  $image = $result[0];
  $dimensions = MapUtils::GetMap($image->dimensions);
  printf("Image with dimensions '%dx%d', MIME type '%s', and id '%s' was "
      . "uploaded.\n", $dimensions['FULL']->width,
      $dimensions['FULL']->height, $image->mimeType, $image->mediaId);
}

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

Upload an HTML5 zip file as a MediaBundle

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

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\MediaBundle;
use Google\AdsApi\AdWords\v201705\cm\MediaMediaType;
use Google\AdsApi\AdWords\v201705\cm\MediaService;
use Google\AdsApi\Common\OAuth2TokenBuilder;
use Google\AdsApi\Common\Util\MapEntries;

/**
 * This example uploads an HTML5 zip file as a MediaBundle.
 */
class UploadImageBundle {

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

    // Create HTML5 media and add it to the list.
    $html5Zip = new MediaBundle();
    $html5Zip->setData(file_get_contents('https://goo.gl/9Y7qI2'));
    $html5Zip->setType(MediaMediaType::MEDIA_BUNDLE);
    $mediaBundles = [$html5Zip];

    // Upload the media bundle to the server.
    $result = $mediaService->upload($mediaBundles);

    // Print out some information about the uploaded image.
    $mediaBundle = $result[0];
    $dimensions = MapEntries::toAssociativeArray($mediaBundle->getDimensions());
    printf(
        "HTML5 media with ID %d, dimensions '%dx%d', MIME type '%s' was "
            . "uploaded.\n",
        $mediaBundle->getMediaId(),
        $dimensions['FULL']->getWidth(),
        $dimensions['FULL']->getHeight(),
        $mediaBundle->getMimeType()
    );
  }

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

UploadImageBundle::main();

Old

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

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

require_once UTIL_PATH . '/MediaUtils.php';
require_once UTIL_PATH . '/MapUtils.php';

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

  // Create HTML5 media.
  $html5Zip = new MediaBundle();
  $html5Zip->data = MediaUtils::GetBase64Data('https://goo.gl/9Y7qI2');
  $html5Zip->type = 'MEDIA_BUNDLE';

  // Make the upload request.
  $result = $mediaService->upload(array($html5Zip));

  // Display result.
  $mediaBundle = $result[0];
  $dimensions = MapUtils::GetMap($mediaBundle->dimensions);
  printf(
      "HTML5 media with ID %d, dimensions '%dx%d', MIME type '%s' was "
          . "uploaded.\n",
              $mediaBundle->mediaId,
              $dimensions['FULL']->width,
              $dimensions['FULL']->height,
              $mediaBundle->mimeType
  );
}

// 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.
  UploadMediaBundleExample($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.