Google Analytics API Tutorial with PHP for Dummies

Build awesome apps with Google Analytics API for PHP. Learn how to use the Google Analytics API and PHP to bring data directly to your site or app.

Build some awesome apps and site functionality with Google Analytics API for PHP.

Recently I needed to build a simple web app that uses the Google Analytics API. Google’s documentation on the subject is a little lackluster and with constant updates to their interface, the documentation often times lags behind. Other times steps are completely left out because they don’t need to hold the hands of dummies like me. Well other dummies, I’m here to hold your hand and walk you through how to use the GA API with PHP.

The Google Analytics API is a powerful tool that allows you to feed information about your site back into just about anything you can build. It’s great for custom dashboards and reports within your own site. Many use it to promote popular pages without having to reply on a database to store the information. Since Google is already collecting it, why not use it? In this Google Analytics API tutorial, I’ll show you how to grab some basic data using the Google Analytics API with PHP like pageviews, time on page, etc.


Google Analytics API Tutorial

Step 1: Create your API keys

First, you’ll need to create a project through the Developers Console.

Create Project

Give your project a name and a unique ID. In this tutorial, we’re going to call our project Analytics API Project and assign analyticsapipro as the project ID..

New Project

Next, we’ll need to switch on the Analytics API. To do this, click on your project and in the left-hand menu under APIs & auth, click APIs. From there you’ll be able to enable the Analytics API.

Enabled APIs

Now we’ll need to create the API keys. In the same menu under APIs & auth, click Credentials. There you should see the Create new Client ID button, click it.

New Client ID

Select Service account, then click the Create Client ID button.

Create Client ID

Your browser will automatically download the private key file you need later. Google will generate a client ID, email address and certificate fingerprint.

Service Account

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:

// 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';

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.

// 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();
}

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.

Author: Ben Marshall

Red Bull Addict, Self-Proclaimed Grill Master, Entrepreneur, Workaholic, Front End Engineer, SEO/SM Strategist, Web Developer, Blogger

3 thoughts on “Google Analytics API Tutorial with PHP for Dummies”

  1. 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 !

  2. 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

Leave a Reply

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