我使用google analytics example,我希望获得关键字列表。对不起,我是分析API的新手,无法找到它的参考。这是从那里复制的代码:
<?php
require_once __DIR__ . '/vendor/autoload.php';
$analytics = initializeAnalytics();
$response = getReport($analytics);
printResults($response);
// Initializes an Analytics Reporting API service object.
function initializeAnalytics()
{
}
// Queries the Analytics Reporting API V4.
function getReport($analytics) {
$VIEW_ID = "xxxx";
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("7daysAgo");
$dateRange->setEndDate("today");
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:sessions");
$sessions->setAlias("sessions");
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges($dateRange);
$request->setMetrics(array($sessions));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analytics->reports->batchGet( $body );
}
// Parses and prints the Analytics Reporting API V4 response.
function printResults($reports) {
for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
$report = $reports[ $reportIndex ];
$header = $report->getColumnHeader();
$dimensionHeaders = $header->getDimensions();
$metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
$rows = $report->getData()->getRows();
for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
$row = $rows[ $rowIndex ];
$dimensions = $row->getDimensions();
$metrics = $row->getMetrics();
for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n");
}
for ($j = 0; $j < count($metrics); $j++) {
$values = $metrics[$j]->getValues();
for ($k = 0; $k < count($values); $k++) {
$entry = $metricHeaders[$k];
print($entry->getName() . ": " . $values[$k] . "\n");
}
}
}
}
}
这会输出给定视图过去七天的会话数,但我想获取关键字。
答案 0 :(得分:1)
您需要在API请求中添加dimensions
参数。像
//Create the Dimensions object.
$keyword = new Google_Service_AnalyticsReporting_Dimension();
$keyword->setName("ga:keyword");
///...
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges($dateRange);
$request->setMetrics(array($sessions));
// Here is an addition
$request->setDimensions(array($keyword));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
您可以在Google Analytics开发网站上找到更多示例:https://developers.google.com/analytics/devguides/reporting/core/v4/samples
请注意,通过这种方式,您只会获得付费关键字的数据,因为在大多数情况下,Google Analytics都不会跟踪有机关键字。