Google Analytics API class for PHP

GA marblesAbout a month back, Google opened the Google Analytics API service to all Analytics users. the API allows developers to integrate the GA reports into their own applications or websites, or even access the reports from a phone!

I’ve been thinking about how I can make use of this API to enhance the sites I’m working on. But before kicking off ideas, I had to find out how to access and use the API. I finally came up with a PHP class that will do all the grunt work of calling the API, you just need to supply your report’s parameter and the PHP class will return you an array of Analytics data.


Getting Started
Ok, first thing’s first, you need to have Google Analytics (obviously) and login credentials to GA. Then you should download my PHP class available at the end of this post.

To access the API is basically a 2 step process. First is to authenticate against Google with your GA account credentials to get an authentication code. After that you can use the authentication code to access your list of website profiles in GA and extract out the data you want.

Google Analytics PHP Class
Here’s how you access a report showing pageviews and visits, by date and country, filtered by ‘Australia’, sorted by pageviews in descending order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
// include the Google Analytics PHP class
include "googleanalytics.class.php";
try {
	// create an instance of the GoogleAnalytics class using your own Google {email} and {password}
	$ga = new GoogleAnalytics('{email}','{password}');
 
	// set the Google Analytics profile you want to access - format is 'ga:123456';
	$ga->setProfile('{GA Profile ID}');
 
	// set the date range we want for the report - format is YYYY-MM-DD
	$ga->setDateRange('2009-04-01','2009-04-07');
 
	// get the report for date and country filtered by Australia, showing pageviews and visits
	$report = $ga->getReport(
		array('dimensions'=>urlencode('ga:date,ga:country'),
			'metrics'=>urlencode('ga:pageviews,ga:visits'),
			'filters'=>urlencode('ga:country=@Australia'),
			'sort'=>'-ga:pageviews'
			)
		);
 
	//print out the $report array
	print_r($report);
 
} catch (Exception $e) { 
	print 'Error: ' . $e->getMessage(); 
}
?>

Hopefully, the code is quite self-explanatory. setProfile() requires your website profile id number. To get the profile id number, you go to your GA dashboard, click on ‘View Report’ for your website, and look at the URL. There should be an ‘id=xxxxxx’ in the URL. That is your id number. You have to specify it as ‘ga:xxxxxxx’ in setProfile().

Profile ID Alternatively, included within the class is a function called getWebsiteProfiles(), if you call this function, after authenticating, you will get an array of all the website profiles available under your account. You can find the id number from there also.

The only major function you need to really pay attention to is the getReport() function. This is where you craft the report parameters that you want results from.

If you’re familiar with GA, you will know that GA basically works with 2 field types – dimensions and metrics. If you’re not sure of what these these things are, I recommend reading the Google documentation on them. Simplistically, you could think of metrics as the columns of your GA reports, and dimensions as the rows.

Google has also listed out the available dimensions and metrics you can use in the API.

With the getReport() function, you are basically doing the same thing as the Custom Reports feature of GA. You decide which dimension and metrics you want and the API will return you the data.

What you will get from getReport() is an array that looks something like this:

Array
(
    [20090401~~Australia] => Array
        (
            [ga:pageviews] => 6
            [ga:visits] => 3
        )
 
    [20090402~~Australia] => Array
        (
            [ga:pageviews] => 4
            [ga:visits] => 3
        )
 
    [20090407~~Australia] => Array
        (
            [ga:pageviews] => 4
            [ga:visits] => 4
        )
 
    [20090403~~Australia] => Array
        (
            [ga:pageviews] => 3
            [ga:visits] => 3
        )
 
    [20090405~~Australia] => Array
        (
            [ga:pageviews] => 3
            [ga:visits] => 3
        )
 
    [20090406~~Australia] => Array
        (
            [ga:pageviews] => 3
            [ga:visits] => 3
        )
 
    [20090404~~Australia] => Array
        (
            [ga:pageviews] => 2
            [ga:visits] => 2
        )
)

To keep the array simple, I’ve basically pushed the dimensions as the 1st array dimension keys, separated by ‘~~’ pattern so that you can parse the keys if you require. The metrics are listed in the sub-array, with the metric as the key and value of the metric.

Do know that not every dimension has a corresponding metric. Google has put up a compatibility chart for you to verify which combination of dimensions and metrics are valid.

This class requires the use of the cURL function in PHP. The functions are normally enabled, but if its not, here a guide on how you enable cURL in PHP.

That’s basically it. Feel free to download the class and play with it. Do bear in mind that this is not a ‘production’ ready class. There’s hardly any validation and error checking and die() is not the best fail-safe method for the class to fail gracefully. When I have more time, I will look at improving the class.. The class has been updated with some exception catching, so hopefully this will give more meaningful error messages for those of you facing problems.

Download: download icon

Here are some more examples of reports you can create:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// what browsers visitors to your using?
$report = $ga->getReport(
	array('dimensions'=>urlencode('ga:browser'),
		'metrics'=>urlencode('ga:visits'),
		'sort'=>'-ga:visits'
		)
	);
 
// which are your top landing pages and how long they spent on the page?
$report = $ga->getReport(
	array('dimensions'=>urlencode('ga:landingPagePath,ga:pageTitle'),
		'metrics'=>urlencode('ga:entrances,ga:timeOnPage'),
		'sort'=>'-ga:entrances'
		)
	);
 
// which are your top internal search keywords by pageviews?
$report = $ga->getReport(
	array('dimensions'=>urlencode('ga:searchKeyword'),
		'metrics'=>urlencode('ga:pageview'),
		'sort'=>'-ga:pageviews'
		)
	);

UPDATE 2009-07-15: Google has posted new updates to the Google Analytics API. The changes includes new limit on the amount of data returned, and relaxed restrictions on combinations of dimensions and metrics.

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • DZone
  • Propeller
  • Reddit
  • StumbleUpon
  • Technorati
  • Yahoo! Buzz
Posted on May 29, 2009 at 5:13 pm by Eldee · Permalink
In: PHP Tutorials · Tagged with: , ,

115 Responses

Subscribe to comments via RSS

  1. [...] ■実際利用してみる ・PHPのライブラリを使用すると楽 http://www.askaboutphp.com/63/google-analytics-api-class-for-php.html [...]

  2. Written by [번역] 구글 아날리틱스 PHP Class on July 13, 2011 at 10:42 pm
    Permalink

    [...] 번역 시작이다. 원문은 Google Analytics API class for PHP [...]

  3. Written by Ryan on August 2, 2011 at 12:19 pm
    Permalink

    thanks for the class Eldee! very useful and time saver!

  4. [...] ・GoogleアナリティクスAPIを使い、定期的に登録したメールアドレスにGoogleアナリティクスのデータを送信します。 ・日々、メールでアクセス状況を把握できますので、PCが無くとも便利に把握できます。 ・オープンソースで提供され、無料で利用できます。 ・使用環境:PHP5、CRON、SENDMAIL、Google Analytics API class for PHP Google Analytics API class for PHP | Ask About PHP [...]

  5. Written by jacke on September 9, 2011 at 4:59 am
    Permalink

    thats a cool library. but why do i get an error if i filter something with a “,”(komma)? Does anybody know that?

  6. Written by Pulsuz sayt on September 23, 2011 at 2:16 am
    Permalink

    Hi,

    Really perfect script :) saved lots of my time!
    I gat a problem on filtering of hostnames. I use:
    ‘filters’=>urlencode(‘ga:hostname=@vsayt.com’)

    I need export only vsayt.com stats but is lists it with all subdomains of same domain. How can i make exact filter of that domain ?

  7. Written by Pulsuz sayt on September 23, 2011 at 2:18 am
    Permalink

    Ahh sorry just find how to do this.
    I need to replace =@ to ==

    Thanks :D

  8. [...] the past few weeks I’ve been using a PHP Google Analytics API Class that I’ve really been enjoying and figured I should make a post to share it with all of you. [...]

  9. [...] ・class.phpmailer.php (メール送信) ・googleanalytics.class.php (GoogleアナリティクスAPI) ※参考 GAPI – Google Analytics API PHP [...]

  10. Written by Marcela on December 17, 2011 at 2:24 am
    Permalink

    Hi,
    Congratulations!
    This script is my salvation, now only i need add the segment, how i cant include the code in the script?

  11. [...] Aquí incluimos dos ficheros esenciales: 1) function_dates.php provee la función createDateRangeArray(), que sirve para crear un array de todos los días que existan entre dos fechas de tu preferencia (ver http://boonedocks.net/mike/archives/137-Creating-a-Date-Range-Array-with-PHP.html); 2) googleanalytics.class.php incluye las instrucciones para conectarse a la API de Google Analytics (ver http://www.askaboutphp.com/63/google-analytics-api-class-for-php.html). [...]

  12. Written by Robert Speer on June 28, 2012 at 1:42 am
    Permalink

    Thanks for this, I’ve used it to create a Google Analytics Reporting plugin for the Apostrophe CMS:

    https://groups.google.com/forum/?fromgroups#!topic/apostrophenow/1EI23QQ3e34

    I did make a small change to add in the API key from google and return json

  13. Written by Ishan Jayman on October 5, 2012 at 12:51 pm
    Permalink

    This api is not working anymore
    https://www.google.com/analytics/feeds/data returns 404

  14. [...] Google Analytics API class for PHP [...]

  15. Written by クリスチャンルブタン ショップ on July 20, 2013 at 4:19 pm
    Permalink

    Google Analytics API class for PHP | Ask About PHP

Subscribe to comments via RSS

Leave a Reply