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 [...]
Permalink
[...] the various sample classes I tried, I would like to thank Eldee for his Google Analytics API PHP and Andrey Savchenko (Rarst) for his Google Chart API which I used [...]
Permalink
Is it in any Way possible to filter after a given pagePath? (just like i do in the interface)?
So that i get, for example, the top 10 Pages with a pagePath that starts with “/search/” ?
Permalink
I have the same error of
“Error: Failed to authenticate, please check your email and password.”
Though i have entered them correctly.Can anyone help?
Permalink
…btw i fix it out… actually …when i was authenticating i
was putting the argument for as $ga = new
GoogleAnalytics(‘{abc@gmail.coml}’,'{mypass}’);
btw i login but there is still no output on the screen.
and the right way was
GoogleAnalytics(‘abc@gmail.com’,'mypass’)
Permalink
Hi Hannes
You can do something like this to get all pagePaths matching your string. In my case, it’s ‘/tutorials/’
$report = $ga->getReport(
array(‘dimensions’=>urlencode(‘ga:pagePath’),
‘metrics’=>urlencode(‘ga:pageviews’),
‘filters’=>urlencode(‘ga:pagePath=~/tutorials/’),
’sort’=>’-ga:pageviews’
)
);
The sort will sort it based on descending order using pageviews as the metric.
Permalink
[...] Google Analytics API class for PHP | Ask About PHP [...]
Permalink
[...] Google Analytics API class for PHP | Ask About PHP http://www.askaboutphp.com/63/google-analytics-api-class-for-php.html →googleanalytics.class.zipをダウンロードして解凍します。 [...]
Permalink
[...] Google Analytics API class for PHP | Ask About PHP [...]
Permalink
[...] Google Analytics API class for PHP | Ask About PHP [...]
Permalink
Hi! Very useful class. I’ve added some kind of cache to the auth code, so the authentication request is made only when necessary. If you want to update the class, please e-mail me.
Thanks!
Permalink
This worked like a charm. I had to fix line 251 like this:
$header[] = ’string’;
As well as I had to set this before line 135:
$dims = NULL;
As it was throwing errors. Thanks a ton for your work! Super handy!
Permalink
how i get the referring sites data from google analytics throught api [gapi.class]?
please someone help me out and tell me how i get this data…
thanks advance
Permalink
thanks For sharing…
Nice information and very usefull
Permalink
Thank you very much for this.
Permalink
[...] 今回はこちらのサイトからダウンロードしました。 http://www.askaboutphp.com/63/google-analytics-api-class-for-php.html [...]
Permalink
Man, can you tell me why i have an error like this:
Fatal error: Call to undefined function curl_init() in Z:\home\localhost\www\googleanalytics.class\googleanalytics.class.php on line 241
Waht’s a problemm? Besides, i used another versions on this Api – again and again this error!
Permalink
Hi Michael, you are getting that error because your PHP doesn’t recognize the curl library call.
Visit this website on how to turn on your curl library
http://www.wallpaperama.com/forums/how-to-find-out-if-php-is-compiled-with-curl-extension-installed-enabled-t1576.html
Permalink
ok, i have fixed it, but i have still problemm. See:
Error: Failed to authenticate, please check your email and password.
Can you help me? I really sure, my login and password are correct!
Permalink
Maybe, format of login or password are incorrect, or Profile?
Permalink
wow, it works! Thank’s great)
Permalink
hi Michael
I’m glad it works. Do remember not to post your login and password for all to see. I’ve edited it out of your previous comment.
Thanks
Permalink
thanks alot…it works and it really helps
Permalink
I tried my gmail with password. I have the profile without the UA and ‘-’. I get the response
GAPI: Failed to request report data. Error: “User does not have permission to access profile [182296141]”
even when I am the admin. Can anyone help with this?
Permalink
hi parunach
did you set the profile id in the correct format? e.g format is ‘ga:123456′ for profile id 123456
Permalink
This is a good script. I added the following lines show that the profile and month selected are displayed to the user.
Install: place this code right after the form.
//show selected profile and month
reset($aProfiles);
foreach ($aProfiles as $sKey => $sValue){
if ($_POST['profileId'] == $sKey) echo ‘Stats for ’.$sValue.’ (‘.date(‘F’, mktime(0, 0, 0, $iMonth, 1, date(‘Y’))).’)';
}
Permalink
Hi,my curl is installed properly but still m getting d error as Permission Denied on line 266
elseif ($info['http_code'] == 401) {
throw new Exception(‘Permission Denied – ‘.$response);
cn someone help..plz
Permalink
THIS API does NOT support SEGMENTS. you need to query the version 2 of the google api and this one queries the v1.
Permalink
[...] Google Analytics API class for PHPという記事でGoogle Analytics APIを簡単に呼び出せるようにするライブラリが公開されていますので 利用させてもらいます。ページ中程にあるダウンロードのリンクからzipファイルをダウンロードし、以下のような構造で配置しました。 [...]
Permalink
Does anyone knows how to get info about custom variables from php analytics api? Is it possible? I’ve didn’t see it in any place.
Permalink
Hi Alex
Does this help?
http://code.google.com/apis/analytics/docs/gdata/gdataReferenceDimensionsMetrics.html#d6CustomVariables
Permalink
[...] Analytics API class for PHP | Ask About PHP http://www.askaboutphp.com/63/google-analytics-api-class-for-php.html [...]
Permalink
Hello, Great job you really saved my day.
I am now trying to get the sum of monthly visits.
How can i read from the array?
when i print $report it say array.
what should i use to read visits from that array?
Permalink
Hi,
is there a way to Limit the Results?
I saw “max-results” at the google Page but it doesnt work?
Permalink
[...] 參考資料 [...]
Permalink
[...] Google Analytics API class for PHP | Ask About PHP PHPによるWordPressカスタマイズブック―2.8対応 テンプレートの改造からプラグインの作成まで posted with amazlet at 10.12.13 藤本 壱 ソシム 売り上げランキング: 149269 Amazon.co.jp で詳細を見る [...]
Permalink
hi
i get NULL even though i know there is data for the dates for the last week.
what am i doing wrong?
best regards
Permalink
Hello,
Thank you very much for this class. This is great.
I am trying to use dynamic segment of the API. It does not work.
Hello said (comment 26138) that your class call the V1 Api. This v1 api does not handle dynamic segment.
On the other side, Google Analytics API says calls are updated automatically.
What about this ??
Permalink
Hello again,
I have just found the solution to use Analytics API v2 and so use dynamic segments :
Add ‘v’=>’2.0′ tu your url parameters.
For example if you want to get all the number of visits under a subpart of the site (here “Conseil”) :
$report = $ga->getReport(
array(‘dimensions’=>urlencode(‘ga:date’),
‘metrics’=>urlencode(‘ga:visits’),
’segment’=>urlencode(‘dynamic::ga:pagePath=~^/Conseils.*’),
’sort’=>’ga:date’,
‘v’=>’2.0′
)
);
So simple ! Thank you again for the class.
Permalink
Thanks for the tutorial.That’s the clearest explanation of the process I have found. And, I’ve been searching on how to do this. Most instructions have not been as clear and as thorough.
Permalink
Thanks for the awesome code! Does anyone here know how to display this information in a chart once it’s gathered? That would be really cool to know. Thanks in advance.
- Pat
Permalink
Hey, I wrote an article in my blog on how to develop amazon-like suggestions with the Google Analytics API and PHP: http://www.kammerath.net/google-analytics-api-fur-amazon-ahnliche-vorschlage.html
Permalink
Hi I used your excellent class on a test page at the start of 2010.
All worked brilliantly well.
I’ve just returned to it a year later and now I’m getting an error reported:
“Error: Bad request – Bad date format: 2011-02-30″
Has anything changed that you’re aware of?