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
I seem to get a permission error when i try to run this
Error: Permission Denied – User does not have permission to access profile [xxxxxxx] does anyone know a way round this?
Permalink
Hello
in the first instance i want to thank for the class published hear, and I would ask, how I can logout an account, to access another account?
I hope you can help me with this little problem
Permalink
Doug,
Thank you for the class. I fixed a couple of bugs and was wondering if you could email me as to where I could submit that changes?
Thanks in advance,
Scott
Permalink
Hi Scott
You can email me at webbie@askaboutphp.com. Thanks!
D.
Permalink
hello now found the problem in this class
add the information login and id
when login i can not login and resulted
Error: Failed to authenticate, please check your email and password.
why ;
no’s when used this information to login in Googleanalytics
i can login and see the analytics site
Permalink
can one use a segment in the api ? I have used a “views with conversion segment”(gaid::-9) but I get the normal data .I get no changes in the data at all .
this is my code
$ga->getReport(array(’dimensions’=>urlencode(’ga:pagePath’),’metrics’=>urlencode(’ga:uniquePageviews’),’segment’=>urlencode(’gaid::-9′),’sort’=>’-ga:uniquePageviews’,'max-results’=>’10′))
When i use the same dimensions and metrics with the same segment in the Query explorer from the google api website I get the reflected changes.
Permalink
Hello,
I tried to use:
$report = $ga->getReport(
array(’dimensions’=>urlencode(’ga:searchKeyword’),
‘metrics’=>urlencode(’ga:pageviews’),
’sort’=>’-ga:pageviews’
)
In this case I get nothing in report:(. At the same time I’m sure that the statistic exists by keywords.
Why the report is empty?
Permalink
[...] iki örnek class içerisinden Google Analytics API PHP class çalışmasından dolayı Eldee’ye ve Google Chart API class çalışmasından dolayı Andrey Savchenko (Rarst)’a teşekkür [...]