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: , ,

72 Responses

Subscribe to comments via RSS

  1. Written by SeanJA on May 29, 2009 at 6:33 pm
    Permalink

    Not sure that you are actually allowed to ask people to click the ads… And why does it say the zip is called pageload.zip? Haven’t tried the code yet, but I will later today.

  2. [...] the Ask About PHP blog today there’s a new tutorial (and a new class) helping you to connect your applications with the Google Analytics backend. [...]

  3. Written by Google Analytics API class for PHP | Ask About PHP on May 30, 2009 at 5:30 am
    Permalink

    [...] more: Google Analytics API class for PHP | Ask About PHP Share and [...]

  4. Written by webmaster on May 30, 2009 at 10:10 am
    Permalink

    hi SeanJA
    thanks for pointing out the graphics mistake. I’ve made the change. I’ll take your advice on the ads things – taking it out.
    Thanks!

  5. Written by Daily Digest for 2009-05-29 | Pedro Trindade on May 30, 2009 at 3:18 pm
    Permalink

    [...] Google Analytics API class for PHP | Ask About PHP This entry was written by trindade, posted on May 29, 2009 at 11:59 pm, filed under Lifestream. Bookmark the permalink. Follow any comments here with the RSS feed for this post. Post a comment or leave a trackback: Trackback URL. « Daily Digest for 2009-05-28 [...]

  6. Written by Google Analytics API Class para PHP | aNieto2K on May 30, 2009 at 5:35 pm
    Permalink

    [...] Hace unas semanas conocimos la noticia de Google Analytics había publicado su API pública para permitir que usáramos nuestros datos almacenados en sus servidores en nuestras aplicaciones. Si estás interesado en ella y además el lenguaje de programación que quieres usar es PHP esta class hará tu vida más fácil. [...]

  7. Written by Google Analytics API Class para PHP : Blogografia on May 30, 2009 at 5:40 pm
    Permalink

    [...] Hace unas semanas conocimos la noticia de Google Analytics había publicado su API pública para permitir que usáramos nuestros datos almacenados en sus servidores en nuestras aplicaciones. Si estás interesado en ella y además el lenguaje de programación que quieres usar es PHP esta class hará tu vida más fácil. [...]

  8. Written by Curtis Gibby on June 1, 2009 at 11:21 pm
    Permalink

    You might want to change the second set of example codes — the metrics variable on the “Top Landing Page” example report has an extra comma in it that will throw an error from Google if someone just copies and pastes it into their code page.

    Change line 12 from “‘metrics’=>urlencode(‘ga:entrances,ga:timeOnPage,’),”
    to
    “‘metrics’=>urlencode(‘ga:entrances,ga:timeOnPage’),”

  9. Written by jason on June 2, 2009 at 4:23 am
    Permalink

    in your getWebsiteProfiles function on line 153, you have if($xml) – it should be if($response)

  10. Written by links for 2009-06-01 « 個人的な雑記 on June 2, 2009 at 6:07 am
    Permalink

    [...] Google Analytics API class for PHP | Ask About PHP (tags: google webservices googleanalytics analytics) [...]

  11. Written by webmaster on June 2, 2009 at 8:46 am
    Permalink

    @Curtis Gibby, @jason
    thanks for pointing out the mistakes. I’ve made the changes, and updated the post.
    thanks again.

  12. [...]  Google Analytics API class for PHP | Ask About PHP  (Google Analytics APIチュートリアル) [...]

  13. [...] Google Analytics API class for PHP | Ask About PHP [...]

  14. Written by Stano on June 9, 2009 at 5:09 am
    Permalink

    Still get: Invalid XML received from API service

  15. Written by webmaster on June 9, 2009 at 8:30 am
    Permalink

    Hi Stano, have you checked the parameters and profileID? you can email me at webbie@askaboutphp.com if you get the error.

  16. Written by José Luis on June 11, 2009 at 8:23 pm
    Permalink

    Hi, i’m algo receiving the “Invalid XML received from API service” error. I’ve checked all the parameters and seems ok.

  17. Written by webmaster on June 13, 2009 at 12:55 am
    Permalink

    Looks like I need to beef up the error reporting a bit better. I’ll post an updated version soon.
    thanks

  18. Written by Robb Luther on June 13, 2009 at 2:13 am
    Permalink

    I am getting the Invalid XML received from API service… I am on a GoDaddy hosting plan… I wonder if the other people running into this issue are too.

  19. Written by webmaster on June 13, 2009 at 11:17 am
    Permalink

    Well, if you’re getting the Invalid XML error, that means you successfully authenticated with your email and password when you created an instance of the class. So would that rule out any connection/hosting related issue?

    Do you guys get the XML error if you try the getWebsiteProfiles() function also? if you don’t, then it’s likely to be the parameters passed.

  20. Written by José Luis on June 15, 2009 at 6:45 pm
    Permalink

    Using getWebsiteProfiles(), error still occurs. getWebsiteProfiles() alone is working.

  21. Written by Jiri Melcak on June 16, 2009 at 6:04 am
    Permalink

    Thank you very much. Script works like a charm.

  22. Written by webmaster on June 16, 2009 at 12:17 pm
    Permalink

    hi Jose
    if getWebsiteProfiles() alone works, then it’s likely the errors are from parameters passed to google api. Maybe the profile id?

    otherwise i don’t know why you would get an invalid xml returned from the google service.

  23. Written by webmaster on June 16, 2009 at 12:48 pm
    Permalink

    Ok people, I’ve updated the class with better error checking. Download the new version. Hopefully it will provide you better information on the errors you get.

  24. Written by José Luis on June 16, 2009 at 10:44 pm
    Permalink

    Same Invalid XML received from API service.

    Maybe there is something with my accocunt. Anyway, thanks for the responses.

  25. Written by Harjit Sandhu on June 18, 2009 at 5:52 pm
    Permalink

    Two errors running under the latest php version.

    googleanalytics.class.php line 251 (roughly)… the value is going in to the $header array as an array. Just change this to a string.

    googleanalytics.class.php line 126 (roughly)… the variable $dim needs to be declare first.

    Other than that… Excellent code… Love It!!! saved me loads of time :)

  26. Written by webmaster on June 19, 2009 at 3:28 pm
    Permalink

    hi Harjit
    thanks for your support and the heads up on the 2 php warnings.

  27. Written by maz on June 22, 2009 at 10:33 pm
    Permalink

    Regarding the error:

    getReport() failed to get a valid XML from Google Analytics API service

    i get this error when my start date is before YYYY-DD-MM 2005-01-01. So if you use a default unix stamp or whatever and generate a date yourself and your default sets the usual 1970-01-01 then the api fails. i am not sure why but i suspect this is an issue with a google start date for analytics rather than an issue with this code – which by the way is really useful – cheers :)

  28. [...] La semana pasada hablaba de la aparición de la API de Google Analytics con la que podríamos aaceder a toda la información de las estadísticas de nuestras páginas, hoy, gracias a Andrés, doy a conocer una clase en PHP para trabajar con la API de Google Analytics. [...]

  29. Written by steve on June 29, 2009 at 11:15 pm
    Permalink

    hi folks,

    I’m using

    foreach ($report as $wert => $value)
    echo ‘Schlüssel: ‘.$wert.’; Wert: ‘.$value[0].”.”\n”;

    I don’t know to set $value[x] properly, just wonna read out the impressions. Can anybody help me out?

    Thanks! And btw ist it possible to track keywords with this?

    Kind refards from germany,
    steve

  30. Written by jon on July 6, 2009 at 4:19 am
    Permalink

    When I attempt to run this I cannot get past this line:

    $ch = curl_init();

    Any ideas?

  31. Written by webmaster on July 7, 2009 at 8:06 pm
    Permalink

    If you can’t get pass the line curl_init(), check your error message. Verify that you have curl installed.

    Here’s the link on how to enable the curl function in php. http://www.wallpaperama.com/forums/how-to-find-out-if-php-is-compiled-with-curl-extension-installed-enabled-t1576.html

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

  33. Written by WaffleSouffle on August 4, 2009 at 8:44 pm
    Permalink

    Line 332 you have:
    $header[] = array(“application/x-www-form-urlencoded”);

    This should probably be:
    $header[] = “application/x-www-form-urlencoded”;

    Also “getReport()” doesn’t declare $results, so I added line 151:
    $results = array();

    Hope that helps.

  34. [...] Google Analytics APIをPHPから扱うありがたいクラスはここ http://www.askaboutphp.com/tutorials/63/google-analytics-api-class-for-php.html [...]

  35. Written by Slawa on August 29, 2009 at 6:02 am
    Permalink

    If you want to write a program which will display the visitors (or pageviews) chart for all your profiles in one page, you make take my prototype as a working source for your own experiments.

    http://spidgorny.blogspot.com/2009/08/seeing-all-googla-analytics-profiles-at.html

  36. Written by Igor on September 6, 2009 at 3:17 am
    Permalink

    I’ve been using this class for a while and it’s always worked great for me. Since last night (9/4), however, I have been getting the error message:

    “getReport() failed to get a valid XML from Google Analytics API service”

    The getWebsiteProfiles() method continues to return correct results, but the getReport() method keeps triggering the error message. I verified that this is the case with several GA accounts that I have, and I also reverted all of my custom changes to the original code published here, but still no luck. It almost appears that this is something on Google’s end, but I couldn’t find anything on their blog, group, or anywhere else. Any tips would be appreciated!

  37. Written by Igor on September 8, 2009 at 2:04 am
    Permalink

    Update: it’s all working for me again. Still not sure what caused the problems I was noticing
    earlier, but it’s possible that it was something unrelated to this class or GA. Hope I didn’t confuse anyone.

  38. Written by http://dealbit.com on September 9, 2009 at 11:42 am
    Permalink

    works great, thanks for the code, but how do you get referring sources using this class?

  39. Written by webmaster on September 10, 2009 at 10:41 am
    Permalink

    I think if you are trying to get referring sources, you need to use the dimension ‘ga:hostname’. Find out more at http://code.google.com/apis/analytics/docs/gdata/gdataReferenceDimensionsMetrics.html#d1Visitor

  40. Written by php thumbnailer on September 11, 2009 at 4:17 pm
    Permalink

    that looks great!

  41. Written by martin on September 28, 2009 at 3:56 pm
    Permalink

    works like a treat. thank you for this great class.

  42. [...] This script depends upon and appreciates the google analytics php class. It can be downloaded in this bundle, or found here: http://www.askaboutphp.com/tutorials/63/google-analytics-api-class-for-php.html [...]

  43. Written by Brett on October 14, 2009 at 12:54 pm
    Permalink

    I’m trying to check for keywords with visits more than 5. I’m using the following:

    $google_lastMonth = $ga->getReport(
    array(‘dimensions’=>urlencode(‘ga:keyword’),
    ‘metrics’=>urlencode(‘ga:visits>5′)
    )
    );

    But I get the following error:
    Error: Bad request – Invalid value for metrics parameter: ga:visits>5

    I’m basing this operation off of this documentation page:
    http://code.google.com/apis/analytics/docs/gdata/gdataReferenceDataFeed.html

    Does this plugin not permit this sort of operation? If so, do you have any suggestions on how to modify it so that it will?

  44. Written by webmaster on October 17, 2009 at 7:33 pm
    Permalink

    Hi Brett
    Thanks for using the class. No that’s not the way to use it. The ‘metrics’ key is for GA’s API to know what metrics you want to return, if you wan to do an expression like visits > 5, you need to use the filter key.

    http://code.google.com/apis/analytics/docs/gdata/gdataReferenceDataFeed.html#filters

    e.g.
    $google_lastMonth = $ga->getReport(
    array(‘dimensions’=>urlencode(‘ga:keyword’),
    ‘metrics’=>urlencode(‘ga:visits’),
    ‘filters’=>urlencode(‘ga:visits>5′)
    )
    );

    Hope this helps

  45. [...] A Google Analytics API-ban használt paraméterek dokumentációja: Dimensions & Metrics Reference. A scripthez felhasznált PHP class: Google Analytics API class. [...]

  46. Written by Rick on November 10, 2009 at 10:48 pm
    Permalink

    Anyone have any suggestions on how to return outbound links?

    We are using Google Analytics suggestion of adding this to outbound links.

    This then shows in Top Content reports the page name (outgoing) in your report.

    How might we use the API to return data on outgoing pages?

  47. Written by Rick on November 10, 2009 at 10:49 pm
    Permalink

    .. sorry that last post should have just printed the hyperlink..

    The link has the following javaScript.

    onClick=”javascript: pageTracker._trackPageview (‘/outgoing/example.co.uk’);”

    As per this Google Analytics Help article. http://www.google.co.uk/support/googleanalytics/bin/answer.py?hl=en-uk&answer=55527

  48. Written by webmaster on November 11, 2009 at 8:00 am
    Permalink

    Hi Rick
    Are you asking how to return the outbound links from the Google Analytics API?

    The dimension I would use is ga:pagePath, and set a filter for ‘outgoing’, you should be able to get what you need.

  49. Written by amorphous_projects on November 17, 2009 at 7:12 am
    Permalink

    Does anyone know if its possible to update via the API? I want to use GA on pages that never send header information so it has to be done in PHP vs. an include.

    Thanks,

  50. Written by webmaster on November 17, 2009 at 11:41 am
    Permalink

    @amorphous_projects
    Not to my knowledge. There’s no means for you to update your GA via the API. It’s all done through javascript.

Subscribe to comments via RSS

Leave a Reply