Skip to content

Instantly share code, notes, and snippets.

@franzose
Last active Aug 15, 2021
Embed
What would you like to do?
Google Analytics Reporting API usage example
<?php
// composer require google/apiclient
require __DIR__ . '/vendor/autoload.php';
// This is the file obtained from Google during the service account creation process
// see these links:
// 1. https://console.developers.google.com/apis/credentials/serviceaccountkey
// 2. https://console.developers.google.com/iam-admin/serviceaccounts/create
$secrets = __DIR__ . '/secrets.json';
$client = new Google_Client();
$client->setApplicationName('Test App');
$client->setAuthConfig($secrets);
$client->setScopes([
'https://www.googleapis.com/auth/analytics.readonly'
]);
$analytics = new Google_Service_AnalyticsReporting($client);
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate('2009-01-01');
$dateRange->setEndDate('2019-07-16');
$pageViews = new Google_Service_AnalyticsReporting_Metric();
$pageViews->setExpression("ga:pageviews");
$pageViews->setAlias('pageviews');
$filter = new Google_Service_AnalyticsReporting_DimensionFilter();
$filter->setOperator('EXACT');
$filter->setDimensionName('ga:pagePath');
$filter->setExpressions([
'/path/to/a/page/'
]);
$filterClause = new Google_Service_AnalyticsReporting_DimensionFilterClause();
$filterClause->setFilters([$filter]);
$request = new Google_Service_AnalyticsReporting_ReportRequest();
// View ID has to be taken from the View Settings of your Google Analytics account
// Note: Reporting API will fail unless View ID is a string
$request->setViewId('01234567890');
$request->setDateRanges($dateRange);
$request->setMetrics([$pageViews]);
$request->setDimensionFilterClauses([$filterClause]);
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests([$request]);
/**
* Here and below we have to deal with incorrect type hints in the generated PHP code
*
* @var Google_Service_AnalyticsReporting_Report $report
*/
$report = $analytics->reports->batchGet($body)->getReports()[0];
/**
* @var Google_Service_AnalyticsReporting_DateRangeValues $total
*/
$total = $report->getData()->getTotals()[0];
// This is the desired page views amount
echo $total->current();
@cdbessig
Copy link

cdbessig commented Jul 22, 2021

Thanks!

@waqasy
Copy link

waqasy commented Aug 15, 2021

It works. Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment