Search volumes - can't get it to work.. PHP

163 views
Skip to first unread message

Mark

unread,
May 23, 2017, 3:26:53 PM5/23/17
to AdWords API Forum
Hello,

I'm trying to save last month's search volume for our product names in our database. Our products are very common brands and models - we sell tires. 

We want to apply these filters:
- Period: last month
- Country: the Netherlands

We have about 4.3k products and since the API is limited to 700 keywords at once I needed to adjust to sample code. I made this:

namespace Google\AdsApi\Examples\AdWords\v201702\Optimization;

require 'vendor/autoload.php';
$path = $_SERVER['DOCUMENT_ROOT'];

define('WP_USE_THEMES', true);


include_once $path . '/wp-load.php';

use Band;




function getFullBandenMerk($merk)
{
return Band::fullMerk($merk);
}


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

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

  const PAGE_LIMIT = 1000;
  const perPage = 699;
  
  
  

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

    // Create selector.
    $selector = new TargetingIdeaSelector();
    $selector->setRequestType(RequestType::STATS);
    $selector->setIdeaType(IdeaType::KEYWORD);
    $selector->setRequestedAttributeTypes([
        AttributeType::KEYWORD_TEXT,
        AttributeType::TARGETED_MONTHLY_SEARCHES,
    ]);
    
    $searchParameters = [];
    
    global $wpdb;
    
    $search = $wpdb->get_results("SELECT DISTINCT merk, beschrijving FROM bc_banden WHERE merk != '' AND beschrijving != ''  LIMIT ".self::perPage." OFFSET ".($page*self::perPage));
    
    $keywords = array();
    
    foreach($search as $item)
    {
   $keyword = trim(str_replace('*', '', str_replace('?', ' ', str_replace('/', ' ', preg_replace("/\([^)]+\)/","", getFullBandenMerk($item->merk).' '.$item->beschrijving)))));
   
   $keywords[] = $keyword;
   
  # echo $keyword.','.PHP_EOL;
    }
    
    
    $keywords = array_unique($keywords);
  
    // Create related to query search parameter.
    $relatedToQuerySearchParameter = new RelatedToQuerySearchParameter();
    $relatedToQuerySearchParameter->setQueries($keywords);
    $searchParameters[] = $relatedToQuerySearchParameter;
    
    $locationData = new LocationSearchParameter();
    $nederland = new Location();
    $nederland->setId(2558);
    $locationData->setLocations([$nederland]);
    $searchParameters[] = $locationData;

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

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

    $selector->setSearchParameters($searchParameters);
    $selector->setPaging(new Paging(0, self::PAGE_LIMIT));

    $totalNumEntries = 0;
        
    do {
      // Retrieve targeting ideas one page at a time, continuing to request
      // pages until all of them have been retrieved.
      $page = $targetingIdeaService->get($selector);

      // Print out some information for each targeting idea.
      if ($page->getEntries() !== null) {
        $totalNumEntries = $page->getTotalNumEntries();
        foreach ($page->getEntries() as $targetingIdea) {
       
          $data = MapEntries::toAssociativeArray($targetingIdea->getData());
          
          $keyword = $data[AttributeType::KEYWORD_TEXT]->getValue();
          $searchVolume =
              ($data[AttributeType::TARGETED_MONTHLY_SEARCHES]->getValue() !== null)
              ? $data[AttributeType::TARGETED_MONTHLY_SEARCHES]->getValue() : 0;

 foreach($searchVolume as $volume)
 {
#  echo $keyword.' '.$volume->getYear().' '.$volume->getMonth().' '.$volume->getCount().PHP_EOL;
 
 $searchvol = $volume->getCount();
   
 $wpdb->query($wpdb->prepare("INSERT INTO bc_banden_searchvolume (searchterm, searchvolume) VALUES (%s, %d) ON DUPLICATE KEY UPDATE searchvolume = %d;", $keyword, $searchvol, $searchvol));
 break;

 }
        }
      }

      $selector->getPaging()->setStartIndex(
          $selector->getPaging()->getStartIndex() + self::PAGE_LIMIT);
    } while ($selector->getPaging()->getStartIndex() < $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();
        
    global $wpdb;
    
    $search = $wpdb->get_results("SELECT DISTINCT merk, beschrijving FROM bc_banden WHERE merk != '' AND beschrijving != ''");
    $results = count($search);
    unset($search);
    $pages = ceil($results/self::perPage);
    
    for($i = 0; $i < $pages; $i++)
    {
    self::runExample(new AdWordsServices(), $session, $i);
    }
    
  }
}

GetKeywordIdeas::main();

But for some reason I only get 18 results inserted in our database, with only 1 keyword that actually has a search volume bigger than 0.. What am I doing wrong? I spend a lot of time debugging but it seems that I only get less results.. When I put my product names in the keyword planner I get results for almost all products. 

My developer key is approved.

Thank you

Shwetha Vastrad (AdWords API Team)

unread,
May 23, 2017, 4:27:09 PM5/23/17
to AdWords API Forum
Hi Mark, 

I see that you are setting the location criterionId as 2558 which corresponds to Nicaragua. The LocationCriterionId for Netherlands is 2528. This could be the reason you see that the search volumes are not being returned as expected. Could you retry the request with the correct LocationCriterionId and let me know if it works? Please see this guide to get the CriteironIds for geo targets. 

Regards,
Shwetha, AdWords API Team.

Mark

unread,
May 24, 2017, 6:31:06 AM5/24/17
to AdWords API Forum
Wow.. that was really stupid from me. I looked the LocationCriterionId up in that table but I wrote it down wrong.. 

Thanks, it works now!
Reply all
Reply to author
Forward
0 new messages