public function getKeywordIdeasByUrlOrWord($clientCustomerId, $input, $languageId, $locationIds = [], $pageUrl = null) {
$keywordPlanIdeaServiceClient = $this->client->getKeywordPlanIdeaServiceClient();
// Create an empty HistoricalMetricsOptions instance
$historicalMetricsOptions = new HistoricalMetricsOptions();
$requestParams = [
'customer_id' => $clientCustomerId,
'language' => $languageId,
'keyword_plan_network' => KeywordPlanNetwork::GOOGLE_SEARCH,
'geo_target_constants' => $locationIds,
'historical_metrics_options' => $historicalMetricsOptions,
'include_adult_keywords' => true,
'keyword_annotation' => [
KeywordPlanKeywordAnnotation::KEYWORD_CONCEPT,
],
'page_size' => 10000
];
if ($pageUrl && $input) {
$requestParams['keyword_and_url_seed'] = new KeywordAndUrlSeed([
'keywords' => [$input],
'url' => $pageUrl
]);
} elseif ($pageUrl) {
$requestParams['url_seed'] = new UrlSeed(['url' => $pageUrl]);
} elseif ($input) {
$keywords = explode(',', $input);
if( count($keywords) > 1 ) {
$requestParams['keyword_seed'] = new KeywordSeed(['keywords' => $keywords]);
} else {
$requestParams['keyword_seed'] = new KeywordSeed(['keywords' => [$input]]);
}
}
$request = new GenerateKeywordIdeasRequest($requestParams);
try {
$response = $keywordPlanIdeaServiceClient->generateKeywordIdeas($request);
} catch (\Exception $e) {
error_log('Error generating keyword ideas: ' . $e->getMessage());
throw $e;
}
$keywordIdeas = [];
error_log( print_r( $response, true ) );
foreach ($response->iterateAllElements() as $result) {
$metrics = $result->getKeywordIdeaMetrics();
error_log( print_r( $result->getKeywordAnnotations(), true ) );
$monthlySearchVolumes = [];
if ($metrics && $metrics->getMonthlySearchVolumes()->count() > 0) {
foreach ($metrics->getMonthlySearchVolumes() as $monthlyVolume) {
$year = $monthlyVolume->getYear();
$monthNumber = $monthlyVolume->getMonth();
$searches = $monthlyVolume->getMonthlySearches();
$monthName = DateTime::createFromFormat('!m', $monthNumber)->format('M');
$monthlySearchVolumes[] = [
'year' => $year,
'month' => $monthName,
'searches' => $searches,
];
}
}
$keywordIdeas[] = [
'keyword' => $result->getText(),
'avg_monthly_searches' => $metrics ? $metrics->getAvgMonthlySearches() : 'N/A',
'competition' => $metrics ? KeywordPlanCompetitionLevel::name($metrics->getCompetition()) : 'N/A',
'competition_index' => $metrics ? $metrics->getCompetitionIndex() : 'N/A',
'low_top_of_page_bid' => $metrics && $metrics->hasLowTopOfPageBidMicros() ? $metrics->getLowTopOfPageBidMicros() / 1_000_000 : 'none',
'high_top_of_page_bid' => $metrics && $metrics->hasHighTopOfPageBidMicros() ? $metrics->getHighTopOfPageBidMicros() / 1_000_000 : 'none',
'monthly_search_volumes' => $monthlySearchVolumes,
];
}
return $keywordIdeas;
}