Google Analytics API

Written by
Published
Updated
Typical Read
5 minutes

Learn how integrate GA traffic data into your app or webpage using the Google Analytics API and PHP. Get useful insights like page views, time on site, popular pages, and more with simple API queries.

tl;dr

Using PHP with the Google Analytics API is easy with Google’s APIs Client Library for PHP. Install the PHP library with composer, then query it as needed. Check out the example below.

/**
 * Include the required composer dependencies.
 */
require_once 'vendor/autoload.php';
// Initialize the Google_Client PHP library.
$client = new Google_Client();
$client->setApplicationName("ApplicationName");
$client->setAssertionCredentials(
  new Google_Auth_AssertionCredentials(
    // Google client ID email address.
    'generated-email@developer.gserviceaccount.com',
    array('https://www.googleapis.com/auth/analytics.readonly'),
    // Downloaded client ID certificate file.
    file_get_contents( 'certificate-filename.p12' )
  )
);
// Google client ID.
$client->setClientId( 'generated-client-id.apps.googleusercontent.com' );
$client->setAccessType( 'offline_access' );
$analytics = new Google_Service_Analytics( $client );
// Google Analytics account view ID.
$analytics_id = 'ga:XXXXXXX';
// Get unique pageviews and average time on page.
try {
  $optParams = array();
  // Required parameter
  $metrics = 'ga:uniquePageviews,ga:avgTimeOnPage';
  $start_date = '2014-01-29';
  $end_date = '2015-01-29';
  // Optional parameters.
  $optParams['filters'] = 'ga:pagePath==/';
  $optParams['dimensions'] = 'ga:pagePath';
  $optParams['sort'] = '-ga:pageviews';
  $optParams['max-results'] = 10;
  $result = $analytics->data_ga->get( 
    $analytics_id,
    $start_date,
    $end_date,
    $metrics,
    $optParams
  );
  if ( $result->getRows() ) {
    print_r( $result->getRows() );
  }
} catch(Exception $e) {
  echo 'There was an error : ' . $e->getMessage();
}

Google Analytics API Tutorial

The Google Analytics API is a powerful tool that allows you to query your Google Analytics account allowing you to create custom dashboards, reports, and website integration.

In this tutorial, we’ll go over how to create a Google project to generate your API credentials, how to install the PHP library with composer, then query the API to retrieve traffic metrics.

Step 1: Generate the API credentials.

In order to retrieve information from the Google Analytics API, you’ll need to generate API credentials that will be used to authorize your application.

Create a Google project.

First, create a project in the Google API Console.

  1. Log in, then click on the project dropdown that appears next to the Google APIs logo in the top right-hand corner of the screen.
  2. Click the ‘NEW PROJECT‘ button in the modal that pops up.
  3. Enter a Project name and select a Location.
Google Analytics API: Create a project.

Enable the Google Analytics API

Next, we’ll enable the Google Analytics API.

  1. Click the ‘ENABLE APIS AND SERVICES‘ button next to the APIs & Services headline.
    Google Analytics API: Enable the API
  2. Search for, select, and enable the Google Analytics API.
    Google Analytics API: Enable the API

Generate the API Credentials

Next, we’ll need to create the credentials by clicking the “CREATE CREDENTIALS” button in the top right-hand corner of the screen.

Google Analytics API

Next, you’ll need to go to your Google Analytics account and add the email address Google generated in the previous step. Once in GA, go to the admin dashboard and navigate to User Management under the Account column.

User Management

From here you can add the email address Google generated.

Email Permission

Step 2: Use PHP to connect to the Google Analytics API

This is where the fun part begins. You’ll need to download the Google Analytics API Client from Github. Unzip it and place it in the docroot of your project (you only really need the src directory). Use Composer to install the dependieces and create the autoload.php file. You’ll also need to place the certificate file your browser downloaded when you created your client ID in the same place.

Let’s create a PHP file called index.php and save it in the docroot. Add the following code:

[php]// Include the Google API PHP client.
require_once( ‘google-api-php-client/autoload.php’ );

// Initialize the Google API.
$client = new Google_Client();
$client->setApplicationName( ‘analyticsapipro’ );

$client->setAssertionCredentials(
new Google_Auth_AssertionCredentials(

// Google client ID email address
‘generated-email@developer.gserviceaccount.com’,
array(‘https://www.googleapis.com/auth/analytics.readonly’),

// Downloaded client ID certificate file
file_get_contents( ‘certificate-filename.p12’ )
)
);

// Google client ID
$client->setClientId( ‘generated-client-id.apps.googleusercontent.com’ );
$client->setAccessType( ‘offline_access’ );

$analytics = new Google_Service_Analytics( $client );

// Google Analytics account view ID
$analytics_id = ‘ga:XXXXXXX’;[/php]

Be sure to update the code with your client ID credentials and analytics account view ID.

Next, you’ll need to write the API class to gather information from your Google Analytics account. In order to make a successful query, the view ID, date range and dimension parameters need to be set. All other parameters are optional. One very useful tool to help build proper queries is Google’s Query Explorer. It’s essentially doing the same thing we’re doing below, but in a pretty interface.

[php]// Get unique pageviews and average time on page.
try {
$optParams = array();

// Required parameter
$metrics = ‘ga:uniquePageviews,ga:avgTimeOnPage’;
$start_date = ‘2014-01-29’;
$end_date = ‘2015-01-29’;

// Optional parameters
// optParams[‘filters’] = ‘ga:pagePath==/’;
// $optParams[‘dimensions’] = ‘ga:pagePath’;
// $optParams[‘sort’] = ‘-ga:pageviews’;
// $optParams[‘max-results’] = ’10’;

$result = $analytics->data_ga->get( $analytics_id,
$start_date,
$end_date, $metrics, $optParams);

if( $result->getRows() ) {
print_r( $result->getRows() );
}
} catch(Exception $e) {
echo ‘There was an error : – ‘ . $e->getMessage();
}[/php]

And viola! This will output a PHP array with the data you need to build some awesome apps.

For more information, check out Google’s Hello Analytics API tutorial that walks through the steps required to access a Google Analytics account, query the Analytics APIs, handle API responses, and output the results. Also, check out these other great resources for playing around with the Analytics API:

Thanks to Austin Hutchison for getting me off to a good start in putting this together.

6 comments on “Google Analytics API”.

Krister

# Nov 19, 2019

Hi,
How do you convert this to automatically collect data each day?

# Oct 14, 2019

Amazingly Great job. These two points are well covered; "Step 1: Create your API keys" and "Step 2: Use PHP to connect to the Google Analytics API". Thanks for sharing this topic "Google Analytics API Tutorial with PHP for Dummies". The best part is the article has all the practical detailing! Keep sharing

# Jun 23, 2018

Hi
Thanks for your good Article
But now when I using This method i get this Error :
Fatal error: Call to undefined method Google_Client::setAssertionCredentials()

I read About this in stackoverflow and other people said change version of google api php client.
what should I do ?!

aysd

# Dec 7, 2016

that’s interesting,
i just find out an answer here.
Actually i am using Google analytics API for a while up to now, i quiet faced the same problem as Alex and honestly i don’t remember how i fixed it, but i am sure it is just a {space} issue that is causing this ! as the coding is taped correctly.
keep sharing

Alexandre Champagne

# May 4, 2015

Hi, I am stuck at the .p12 file..
I get this error :
// There was an error : – Unable to parse the p12 file. Is this a .p12 file? Is the password correct? OpenSSL error:

Did you forget something ? I see post asking me to pass the file through SSL (which I don’t know how to do ). Plz I really need help haha I’m stuck !

# Jun 17, 2015

Ensure it’s a .p12 and hasn’t been modified at all from the one that get’s downloaded to your computer. Can I see the code you’re using?

Join the conversation.

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

All comments posted on 'Google Analytics API' are held for moderation and only published when on topic and not rude. Get a gold star if you actually read & follow these rules.

You may write comments in Markdown. This is the best way to post any code, inline like `<div>this</div>` or multiline blocks within triple backtick fences (```) with double new lines before and after.

Want to tell me something privately, like pointing out a typo or stuff like that? Contact Me.