Skip to content

Instantly share code, notes, and snippets.

Last active Aug 15, 2021
What would you like to do?
Google Analytics Reporting API usage example
// 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.
// 2.
$secrets = __DIR__ . '/secrets.json';
$client = new Google_Client();
$client->setApplicationName('Test App');
$analytics = new Google_Service_AnalyticsReporting($client);
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$pageViews = new Google_Service_AnalyticsReporting_Metric();
$filter = new Google_Service_AnalyticsReporting_DimensionFilter();
$filterClause = new Google_Service_AnalyticsReporting_DimensionFilterClause();
$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
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
* 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();
Copy link

cdbessig commented Jul 22, 2021


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