使用 Google Analytics Reporting API v4 添加 ga:pagePath 维度以获取特定 URL 的页面浏览量
Adding ga:pagePath dimension to get page views for a particular URL using Google Analytics Reporting API v4
查询资源管理器 (https://ga-dev-tools.appspot.com/query-explorer/) 指定添加过滤器 ga:pagePath 并将 URL 作为值以获取特定 URL.
对于新报告 API,我尝试添加 ga:pagePath 作为维度,但 returns 没有结果。这是代码:
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("7daysAgo");
$dateRange->setEndDate("today");
// Create the Metrics object.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:pageviews");
$sessions->setAlias("pageviews");
//Create the browser dimension.
$path = new Google_Service_AnalyticsReporting_Dimension();
$path->setName("ga:pagePath");
// Create the segment dimension.
$segmentDimensions = new Google_Service_AnalyticsReporting_Dimension();
$segmentDimensions->setName("ga:segment");
// Create Dimension Filter.
$dimensionFilter = new Google_Service_AnalyticsReporting_SegmentDimensionFilter();
$dimensionFilter->setDimensionName("ga:pagePath");
$dimensionFilter->setOperator("EXACT");
$dimensionFilter->setExpressions(array("/post/digital-footprints-the-trails-you-leave-on-the-web"));
// Create Segment Filter Clause.
$segmentFilterClause = new Google_Service_AnalyticsReporting_SegmentFilterClause();
$segmentFilterClause->setDimensionFilter($dimensionFilter);
// Create the Or Filters for Segment.
$orFiltersForSegment = new Google_Service_AnalyticsReporting_OrFiltersForSegment();
$orFiltersForSegment->setSegmentFilterClauses(array($segmentFilterClause));
// Create the Simple Segment.
$simpleSegment = new Google_Service_AnalyticsReporting_SimpleSegment();
$simpleSegment->setOrFiltersForSegment(array($orFiltersForSegment));
// Create the Segment Filters.
$segmentFilter = new Google_Service_AnalyticsReporting_SegmentFilter();
$segmentFilter->setSimpleSegment($simpleSegment);
// Create the Segment Definition.
$segmentDefinition = new Google_Service_AnalyticsReporting_SegmentDefinition();
$segmentDefinition->setSegmentFilters(array($segmentFilter));
// Create the Dynamic Segment.
$dynamicSegment = new Google_Service_AnalyticsReporting_DynamicSegment();
$dynamicSegment->setSessionSegment($segmentDefinition);
$dynamicSegment->setName("Pageview for the URL");
// Create the Segments object.
$segment = new Google_Service_AnalyticsReporting_Segment();
$segment->setDynamicSegment($dynamicSegment);
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges($dateRange);
$request->setDimensions(array($path, $segmentDimensions));
$request->setSegments(array($segment));
$request->setMetrics(array($sessions));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analytics->reports->batchGet( $body );
如有任何帮助,我们将不胜感激。基本上我正在尝试创建一个 Cron Job,它将使用 Google Analytics Reporting API 来获取我网站上各种文章的综合浏览量,并在数据库中更新相同的内容,这将完成一次或者一天两次。下面是我目前用来打印报告的代码:
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");
}
}
}
}
}
我找到了解决这个问题的方法。但是,我没有选择面向对象的方法,而是选择一个数组来生成查询。希望能帮到您解决问题。
// 加载 Google API PHP 客户端库。
require_once __DIR__ . '/vendor/autoload.php';
$VIEW_ID = "replace_with_your_id";
$start_date = "2017-01-01";
$end_date = "2017-12-31";
$analytics = initializeAnalytics();
$reports = getReports("/f/0w3ciqnw");
if ($reports) echo getViews($reports);
/**
* Initializes an Analytics Reporting API V4 service object.
*
* @return An authorized Analytics Reporting API V4 service object.
*/
function initializeAnalytics()
{
// Use the developers console and download your service account
// credentials in JSON format. Place them in this directory or
// change the key file location if necessary.
$KEY_FILE_LOCATION = '../service-account-credentials.json';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("FriendChip Analytics Reporting");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new Google_Service_AnalyticsReporting($client);
return $analytics;
}
function getReports($page_path)
{
global $VIEW_ID, $start_date, $end_date, $analytics;
$query = [
"viewId" => $VIEW_ID,
"dateRanges" => [
"startDate" => $start_date,
"endDate" => $end_date
],
"metrics" => [
"expression" => "ga:pageviews"
],
"dimensions" => [
"name" => "ga:pagepath"
],
"dimensionFilterClauses" => [
'filters' => [
"dimension_name" => "ga:pagepath",
"operator" => "ENDS_WITH", // valid operators can be found here: https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet#FilterLogicalOperator
"expressions" => $page_path
]
]
];
// build the request and response
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests(array($query));
// now batchGet the results https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet
$report = $analytics->reports->batchGet($body);
return $report;
}
function getViews($reports)
{
$rows = $reports[0]->getData()->getRows();
if ($rows){
$metrics = $rows[0]->getMetrics()[0]->values[0];
if ($metrics){
return $metrics;
}
}
return false;
}
我尝试了代码并且运行良好,但只有一个过滤器。
它不适用于两个过滤器:
"metrics" => [
"expression" => "ga:pageviews"
],
"dimensions" => [
"name" => "ga:pagepath",
"name" => "ga:medium",
"name" => "ga:week"
],
"dimensionFilterClauses" => [
'filters' => [
"dimension_name" => "ga:medium",
"operator" => "EXACT",
"expressions" => "organic"
],
'filters' => [
"dimension_name" => "ga:pagepath",
"operator" => "EXACT",
"expressions" => $page_path
]
]
可以找到有效的运算符 here。
查询资源管理器 (https://ga-dev-tools.appspot.com/query-explorer/) 指定添加过滤器 ga:pagePath 并将 URL 作为值以获取特定 URL.
对于新报告 API,我尝试添加 ga:pagePath 作为维度,但 returns 没有结果。这是代码:
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("7daysAgo");
$dateRange->setEndDate("today");
// Create the Metrics object.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:pageviews");
$sessions->setAlias("pageviews");
//Create the browser dimension.
$path = new Google_Service_AnalyticsReporting_Dimension();
$path->setName("ga:pagePath");
// Create the segment dimension.
$segmentDimensions = new Google_Service_AnalyticsReporting_Dimension();
$segmentDimensions->setName("ga:segment");
// Create Dimension Filter.
$dimensionFilter = new Google_Service_AnalyticsReporting_SegmentDimensionFilter();
$dimensionFilter->setDimensionName("ga:pagePath");
$dimensionFilter->setOperator("EXACT");
$dimensionFilter->setExpressions(array("/post/digital-footprints-the-trails-you-leave-on-the-web"));
// Create Segment Filter Clause.
$segmentFilterClause = new Google_Service_AnalyticsReporting_SegmentFilterClause();
$segmentFilterClause->setDimensionFilter($dimensionFilter);
// Create the Or Filters for Segment.
$orFiltersForSegment = new Google_Service_AnalyticsReporting_OrFiltersForSegment();
$orFiltersForSegment->setSegmentFilterClauses(array($segmentFilterClause));
// Create the Simple Segment.
$simpleSegment = new Google_Service_AnalyticsReporting_SimpleSegment();
$simpleSegment->setOrFiltersForSegment(array($orFiltersForSegment));
// Create the Segment Filters.
$segmentFilter = new Google_Service_AnalyticsReporting_SegmentFilter();
$segmentFilter->setSimpleSegment($simpleSegment);
// Create the Segment Definition.
$segmentDefinition = new Google_Service_AnalyticsReporting_SegmentDefinition();
$segmentDefinition->setSegmentFilters(array($segmentFilter));
// Create the Dynamic Segment.
$dynamicSegment = new Google_Service_AnalyticsReporting_DynamicSegment();
$dynamicSegment->setSessionSegment($segmentDefinition);
$dynamicSegment->setName("Pageview for the URL");
// Create the Segments object.
$segment = new Google_Service_AnalyticsReporting_Segment();
$segment->setDynamicSegment($dynamicSegment);
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges($dateRange);
$request->setDimensions(array($path, $segmentDimensions));
$request->setSegments(array($segment));
$request->setMetrics(array($sessions));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analytics->reports->batchGet( $body );
如有任何帮助,我们将不胜感激。基本上我正在尝试创建一个 Cron Job,它将使用 Google Analytics Reporting API 来获取我网站上各种文章的综合浏览量,并在数据库中更新相同的内容,这将完成一次或者一天两次。下面是我目前用来打印报告的代码:
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");
}
}
}
}
}
我找到了解决这个问题的方法。但是,我没有选择面向对象的方法,而是选择一个数组来生成查询。希望能帮到您解决问题。
// 加载 Google API PHP 客户端库。
require_once __DIR__ . '/vendor/autoload.php';
$VIEW_ID = "replace_with_your_id";
$start_date = "2017-01-01";
$end_date = "2017-12-31";
$analytics = initializeAnalytics();
$reports = getReports("/f/0w3ciqnw");
if ($reports) echo getViews($reports);
/**
* Initializes an Analytics Reporting API V4 service object.
*
* @return An authorized Analytics Reporting API V4 service object.
*/
function initializeAnalytics()
{
// Use the developers console and download your service account
// credentials in JSON format. Place them in this directory or
// change the key file location if necessary.
$KEY_FILE_LOCATION = '../service-account-credentials.json';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("FriendChip Analytics Reporting");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new Google_Service_AnalyticsReporting($client);
return $analytics;
}
function getReports($page_path)
{
global $VIEW_ID, $start_date, $end_date, $analytics;
$query = [
"viewId" => $VIEW_ID,
"dateRanges" => [
"startDate" => $start_date,
"endDate" => $end_date
],
"metrics" => [
"expression" => "ga:pageviews"
],
"dimensions" => [
"name" => "ga:pagepath"
],
"dimensionFilterClauses" => [
'filters' => [
"dimension_name" => "ga:pagepath",
"operator" => "ENDS_WITH", // valid operators can be found here: https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet#FilterLogicalOperator
"expressions" => $page_path
]
]
];
// build the request and response
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests(array($query));
// now batchGet the results https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet
$report = $analytics->reports->batchGet($body);
return $report;
}
function getViews($reports)
{
$rows = $reports[0]->getData()->getRows();
if ($rows){
$metrics = $rows[0]->getMetrics()[0]->values[0];
if ($metrics){
return $metrics;
}
}
return false;
}
我尝试了代码并且运行良好,但只有一个过滤器。
它不适用于两个过滤器:
"metrics" => [
"expression" => "ga:pageviews"
],
"dimensions" => [
"name" => "ga:pagepath",
"name" => "ga:medium",
"name" => "ga:week"
],
"dimensionFilterClauses" => [
'filters' => [
"dimension_name" => "ga:medium",
"operator" => "EXACT",
"expressions" => "organic"
],
'filters' => [
"dimension_name" => "ga:pagepath",
"operator" => "EXACT",
"expressions" => $page_path
]
]
可以找到有效的运算符 here。