Google Analytics V4 pagination


Please Share

Google Analytics
Are you working on an application that needs to access Google Analytics data. Would you like to extract your Google analytics data? The Google Analytics Reporting API allows us to do just that. Once we are authenticated we can access a users Google Analytics data. In this tutorial I am going to show you how to extract Google analytics data using php with pagination.

Actually I ran across a question on stackoverflow yesterday How to get the next 10,000 data from google analytics api using php? I felt bad for Ben I knew how hard it was to work this out with C# last year. So I thought I would spend an hour working it out for PHP. Pagination in the Google Analytics v4 is different than the other APIs due to the batching nature of this api. The normal methods of pagination will not work with this API, we need to play with it a little. This code is meant to be used with only one report if you have more then one report your going to have to loop though the response and apply the page tokens to your original request where needed.


Prerequisite

The preferred method is via composer. Follow the installation instructions composer intro if you do not already have composer installed.

Once composer is installed, execute the following command in your project root to install this library:

composer require google/apiclient:^2.0

Authentication

Google Analytics data is private user data in order to access it we must request access of the user, by authenticating our application. When this method is run a web browser will open requesting access to the user Google Analytics data. We are only asking for read only access, it is best to only request the permissions that you actually need. The users authentication will be stored on the local pc so that the user will not need to authenticate again.

Check below for the two files needed for authentication in this tutorial.


$client = getOauth2Client();

// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
	$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
	file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}

$service = new Google_Service_AnalyticsReporting($client); 

Requesting Data

Once we are authenticated we can request data. Please check the dimension and metric reference for a full list of all the dimensions and metrics that can be used with the Google Analytics API.

Note: This is only going to work in if you have a single report in your request. If you have more then one then you are going to have to loop though the reports applying the page token where needed. Remove cnt if you want to return all of the data, I didnt want to eat up my quota in testing.


   $service = new Google_Service_AnalyticsReporting($client); 
// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("2016-01-01");
$dateRange->setEndDate("2017-06-30");

// Create the Metrics object.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:sessions");
$sessions->setAlias("sessions");

//Create the Dimensions object.
$date = new Google_Service_AnalyticsReporting_Dimension();
$date->setName("ga:date");
$pagePath = new Google_Service_AnalyticsReporting_Dimension();
$pagePath->setName("ga:pagePath");

// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId("81692014");
$request->setPageSize("10000");
$request->setDateRanges($dateRange);
$request->setDimensions(array($date,$pagePath));
$request->setMetrics(array($sessions));
$request->setMetrics(array($sessions));

$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
$data =  $service->reports->batchGet( $body );


//showData($data->reports[0]);
$cnt = 0; 
while ($data->reports[0]->nextPageToken > 0 && $cnt < 10) {
	// There are more rows for this report.
	$body->reportRequests[0]->setPageToken($data->reports[0]->nextPageToken);
	$data =  $service->reports->batchGet( $body );
	showData($data->reports[0]->nextPageToken);
	$cnt++;
	}

Full Script


Conclusion

You should now know how to authenticate a php script using Oauth2. Once you are authenticated you will be able to access the users Google Analytics data. There are additional samples for using the Google Analytics Reporting API with php on the Google Analytics website.

Please Share


Linda Lawton

About Linda Lawton

My name is Linda Lawton I have more than 20 years experience working as an application developer and a database expert. I have also been working with Google APIs since 2012 and I have been contributing to the Google .Net client library since 2013. In 2013 I became a a Google Developer Experts for Google Analytics.

Leave a comment

Your email address will not be published. Required fields are marked *