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.
Published
Updated
Typical Read
4 minutes
Sponsored
Do you have a great article to share you want to contribute? Contact me about your idea.
Find your next web developer job
jobs by Indeed

Google Analytics API Tutorial with PHP for Dummies was originally published on Jan 29, 2015 and has recently been updated on Aug 6, 2020 to reflect emerging trends.

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.

Did you find Google Analytics API Tutorial with PHP for Dummies useful? Get articles in your inbox.

…and don’t worry, I hate spam as much as you. Expect to hear from me at most once a week.

Latest Job Postings
Posted on Aug 9, 2020 at 9:17pm
Full-time
Los Angeles
Posted on Aug 9, 2020 at 9:15pm
Full-time
Los Angeles
Posted on Aug 9, 2020 at 1:19am
Littleton, CO
jobs by Indeed
Sponsored
Do you run a development agency, freelance developer or offer website services. Contact me today for information about advertising.
Sponsored
Do you run a development agency, freelance developer or offer website services. Contact me today for information about advertising.
Sponsored
Sponsor my site by donating to help support open-source projects, like WordPress Zero Spam, Referrer Analytics & others.
Sponsored
Help support open-source projects & pro-bono non-profit services by donating today.
Sponsored
Sponsor my site by donating to help support open-source projects, like WordPress Zero Spam, Referrer Analytics & others.

6 Comments on “Google Analytics API Tutorial with PHP for Dummies”

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?

Leave a Reply

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

All comments posted on 'Google Analytics API Tutorial with PHP for Dummies' 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.