Google Analytics API class for PHP
About 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().
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 . The class has been updated with some exception catching, so hopefully this will give more meaningful error messages for those of you facing problems. 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.
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.
In: PHP Tutorials · Tagged with: api, google analytics, php class

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.
Permalink
[...] 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. [...]
Permalink
[...] more: Google Analytics API class for PHP | Ask About PHP Share and [...]
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!
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 [...]
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. [...]
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. [...]
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’),”
Permalink
in your getWebsiteProfiles function on line 153, you have if($xml) – it should be if($response)
Permalink
[...] Google Analytics API class for PHP | Ask About PHP (tags: google webservices googleanalytics analytics) [...]
Permalink
@Curtis Gibby, @jason
thanks for pointing out the mistakes. I’ve made the changes, and updated the post.
thanks again.
Permalink
[...] Google Analytics API class for PHP | Ask About PHP (Google Analytics APIチュートリアル) [...]
Permalink
[...] Google Analytics API class for PHP | Ask About PHP [...]
Permalink
Still get: Invalid XML received from API service
Permalink
Hi Stano, have you checked the parameters and profileID? you can email me at webbie@askaboutphp.com if you get the error.
Permalink
Hi, i’m algo receiving the “Invalid XML received from API service” error. I’ve checked all the parameters and seems ok.
Permalink
Looks like I need to beef up the error reporting a bit better. I’ll post an updated version soon.
thanks
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.
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.
Permalink
Using getWebsiteProfiles(), error still occurs. getWebsiteProfiles() alone is working.
Permalink
Thank you very much. Script works like a charm.
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.
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.
Permalink
Same Invalid XML received from API service.
Maybe there is something with my accocunt. Anyway, thanks for the responses.
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
Permalink
hi Harjit
thanks for your support and the heads up on the 2 php warnings.
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
Permalink
[...] 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. [...]
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
Permalink
When I attempt to run this I cannot get past this line:
$ch = curl_init();
Any ideas?
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
Permalink
[...] Google Analytics API class for PHP [...]
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.
Permalink
[...] Google Analytics APIをPHPから扱うありがたいクラスはここ http://www.askaboutphp.com/tutorials/63/google-analytics-api-class-for-php.html [...]
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
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!
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.
Permalink
works great, thanks for the code, but how do you get referring sources using this class?
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
Permalink
that looks great!
Permalink
works like a treat. thank you for this great class.
Permalink
[...] 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 [...]
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?
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
Permalink
[...] 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. [...]
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?
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
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.
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,
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.