【发布时间】:2021-08-18 02:34:49
【问题描述】:
我们在 Google Analytics(分析)中有几个视图,我们通过他们的API 生成报告。在获取用户数量或会话数量方面,这些视图现在对我们来说效果很好。但是,对于其中一个视图,我们希望深入到特定页面。
例如,我们想知道从July 2021 到August 2021 访问过my-page.php 的用户数。
这是我当前的代码:
// Create and configure a new client object
$client = new Google_Client();
$client->setApplicationName("Analytics");
$client->setAuthConfig(__ROOT__ . '/analytics/client_secrets.json');
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new Google_Service_AnalyticsReporting($client);
// Create DateRange objects.
$july = new Google_Service_AnalyticsReporting_DateRange();
$july->setStartDate("2021-07-01");
$july->setEndDate("2021-07-31");
$august = new Google_Service_AnalyticsReporting_DateRange();
$august->setStartDate("2021-08-01");
$august->setEndDate("2021-08-31");
// Create the Metrics object.
$metric = new Google_Service_AnalyticsReporting_Metric();
$metric->setExpression("ga:users");
$metric->setAlias("users");
//Create the Dimensions object.
$dimension = new Google_Service_AnalyticsReporting_Dimension();
$dimension->setName("ga:pagePath");
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId("XXXX");
$request->setDateRanges(array($july, $august));
$request->setDimensions(array($dimension));
$request->setMetrics(array($metric));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests(array($request));
$reports = $analytics->reports->batchGet($body);
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] . "<br>");
}
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] . "<br>");
}
}
}
}
您会注意到我正在使用ga:pagePath,但我不确定我是否朝着正确的方向前进,因为它提供了我在这两个月内访问过的所有页面,我看不出有任何过滤方法只是我想看到的页面。
如果有帮助,这就是我的代码给出的结果:
...
ga:pagePath: /some/path/other-page.php
users: 388
users: 208
ga:pagePath: /some/path/my-page.php <------ I want this
users: 417
users: 376
ga:pagePath: /wrong/path/wrong-page.php
users: 128
users: 87
...
我想提一下,我们可以通过以下方式完成something similar from the Google Analytics front-end:
Behavior > Site Content > All Pages
然后搜索my-page.php。这就是我想通过 API 复制的内容。
【问题讨论】:
标签: php google-analytics google-analytics-api