Skip to content

Instantly share code, notes, and snippets.

@tuananhzippy
Forked from ko31/SampleFilterAnalytics.php
Created January 19, 2022 03:05
Show Gist options
  • Save tuananhzippy/236e0f188c7097668b7818593d275e20 to your computer and use it in GitHub Desktop.
Save tuananhzippy/236e0f188c7097668b7818593d275e20 to your computer and use it in GitHub Desktop.
Get reports with multiple condition filters for Google Analytics Reporting API v4
<?php
// composer require google/apiclient
/**
* @link https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-php
* @link https://developers.google.com/analytics/devguides/reporting/core/v4/samples
* @link https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet
*/
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
$analytics = initializeAnalytics();
$response = getReport($analytics);
printResults($response);
/**
* 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 = __DIR__ . '/service-account-credentials.json';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("Hello Analytics Reporting");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new Google_Service_AnalyticsReporting($client);
return $analytics;
}
/**
* Queries the Analytics Reporting API V4.
*
* @param service An authorized Analytics Reporting API V4 service object.
* @return The Analytics Reporting API V4 response.
*/
function getReport($analytics) {
// Replace with your view ID, for example XXXX.
$VIEW_ID = "<REPLACE_WITH_VIEW_ID>";
// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("7daysAgo");
$dateRange->setEndDate("today");
// Create the Dimensions object.
$pathDimension = new Google_Service_AnalyticsReporting_Dimension;
$pathDimension->setName("ga:pagePath");
$titleDimension = new Google_Service_AnalyticsReporting_Dimension;
$titleDimension->setName('ga:pageTitle');
// Create the Metrics object.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:sessions");
$sessions->setAlias("sessions");
// Create the DimensionFilter object.
$dimensionFilter = new Google_Service_AnalyticsReporting_DimensionFilter();
$dimensionFilter->setDimensionName('ga:pagePath');
$dimensionFilter->setOperator('REGEXP');
$dimensionFilter->setExpressions('^(\/2018)(.*)+\/$');
$dimensionFilterExclude = new Google_Service_AnalyticsReporting_DimensionFilter();
$dimensionFilterExclude->setDimensionName('ga:pagePath');
$dimensionFilterExclude->setOperator('REGEXP');
$dimensionFilterExclude->setExpressions('^(\/201812)(.*)+\/$');
$dimensionFilterExclude->setNot(true);
$dimensionFilterClause = new Google_Service_AnalyticsReporting_DimensionFilterClause;
$dimensionFilterClause->setFilters([$dimensionFilter, $dimensionFilterExclude]);
$dimensionFilterClause->setOperator( 'and' );
// Create the Order object.
$sessionsOrderByDesc = new Google_Service_AnalyticsReporting_OrderBy;
$sessionsOrderByDesc->setFieldName('ga:sessions');
$sessionsOrderByDesc->setSortOrder('DESCENDING');
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDimensions([$pathDimension, $titleDimension]);
$request->setDateRanges($dateRange);
$request->setMetrics(array($sessions));
$request->setDimensionFilterClauses($dimensionFilterClause);
$request->setOrderBys($sessionsOrderByDesc);
$request->setPageSize(10);
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analytics->reports->batchGet( $body );
}
/**
* Parses and prints the Analytics Reporting API V4 response.
*
* @param An 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");
}
}
}
}
}
@tuananhzippy
Copy link
Author

Screen Shot 2022-01-19 at 10 34 59

Screen Shot 2022-01-19 at 09 41 29

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