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. Written by stephen on November 30, 2009 at 7:55 pm
    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?

  2. Written by yeran on November 30, 2009 at 10:03 pm
    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

  3. Written by Scott on December 16, 2009 at 4:14 am
    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

  4. Written by webmaster on December 16, 2009 at 9:17 am
    Permalink

    Hi Scott
    You can email me at webbie@askaboutphp.com. Thanks!
    D.

  5. Written by Momen on December 30, 2009 at 12:11 pm
    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

  6. Written by Justin on January 15, 2010 at 10:52 pm
    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.

  7. Written by Anthony on January 18, 2010 at 10:55 pm
    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?

  8. [...] 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 [...]

  9. [...] 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 [...]

  10. Written by Hannes on February 9, 2010 at 7:18 pm
    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/” ?

  11. Written by l0gk on February 22, 2010 at 11:09 pm
    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?

  12. Written by dorjay on February 23, 2010 at 2:11 am
    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}’);
    and the right way was
    GoogleAnalytics(‘abc@gmail.com’,'mypass’) :) btw i login but there is still no output on the screen. :(

  13. Written by webmaster on February 24, 2010 at 5:31 pm
    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.

  14. Written by 今日も今日とてお勉強♪ - www.be-styles.jp on March 27, 2010 at 6:46 pm
    Permalink

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

  15. [...] Google Analytics API class for PHP | Ask About PHP http://www.askaboutphp.com/63/google-analytics-api-class-for-php.html →googleanalytics.class.zipをダウンロードして解凍します。   [...]

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

  17. Written by Bruce on May 19, 2010 at 10:30 pm
    Permalink

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

  18. Written by Jonatan on June 6, 2010 at 1:44 pm
    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!

  19. Written by Shawn Adrian on June 16, 2010 at 7:35 am
    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!

  20. Written by ahtsham on July 2, 2010 at 2:06 am
    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

  21. Written by eric on July 15, 2010 at 5:23 am
    Permalink

    thanks For sharing…
    Nice information and very usefull :)

  22. Written by Zachary Burt on July 27, 2010 at 4:48 pm
    Permalink

    Thank you very much for this.

  23. [...] 今回はこちらのサイトからダウンロードしました。 http://www.askaboutphp.com/63/google-analytics-api-class-for-php.html [...]

  24. Written by Michael on August 20, 2010 at 9:40 pm
    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!

  25. Written by webmaster on August 21, 2010 at 12:27 am
    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

  26. Written by Michael on August 21, 2010 at 12:56 am
    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!

  27. Written by Michael on August 21, 2010 at 12:58 am
    Permalink

    Maybe, format of login or password are incorrect, or Profile?

  28. Written by Michael on August 21, 2010 at 1:07 am
    Permalink

    wow, it works! Thank’s great)

  29. Written by webmaster on August 22, 2010 at 6:57 am
    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

  30. Written by martin on August 24, 2010 at 7:26 pm
    Permalink

    thanks alot…it works and it really helps

  31. Written by parunach on September 1, 2010 at 2:58 am
    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?

  32. Written by webmaster on September 1, 2010 at 7:46 am
    Permalink

    hi parunach
    did you set the profile id in the correct format? e.g format is ‘ga:123456′ for profile id 123456

  33. Written by tef on September 2, 2010 at 6:06 pm
    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’))).’)';
    }

  34. Written by Neha on September 23, 2010 at 2:04 pm
    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

  35. Written by hello on October 20, 2010 at 7:46 pm
    Permalink

    THIS API does NOT support SEGMENTS. you need to query the version 2 of the google api and this one queries the v1.

  36. [...] Google Analytics API class for PHPという記事でGoogle Analytics APIを簡単に呼び出せるようにするライブラリが公開されていますので 利用させてもらいます。ページ中程にあるダウンロードのリンクからzipファイルをダウンロードし、以下のような構造で配置しました。 [...]

  37. Written by Alex Valls on November 2, 2010 at 10:55 pm
    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.

  38. Written by webmaster on November 3, 2010 at 9:40 pm
    Permalink
  39. [...] Analytics API class for PHP | Ask About PHP http://www.askaboutphp.com/63/google-analytics-api-class-for-php.html [...]

  40. Written by George on November 9, 2010 at 7:26 pm
    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?

  41. Written by korbe on November 16, 2010 at 12:44 am
    Permalink

    Hi,
    is there a way to Limit the Results?
    I saw “max-results” at the google Page but it doesnt work?

  42. Written by 利用 Google Analytics API 抓取資料-PHP » ed tech on December 2, 2010 at 2:43 pm
    Permalink

    [...] 參考資料 [...]

  43. Written by Google Analytics Data Handler : カグア! on December 13, 2010 at 6:31 am
    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 で詳細を見る [...]

  44. Written by ron on December 27, 2010 at 3:53 pm
    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

  45. Written by Paul Etienney on January 10, 2011 at 3:47 pm
    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 ??

  46. Written by Paul Etienney on January 10, 2011 at 4:08 pm
    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.

  47. Written by google analytics php on January 14, 2011 at 7:10 pm
    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.

  48. Written by Pat on January 30, 2011 at 6:35 am
    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

  49. Written by Jan Kammerath on March 26, 2011 at 2:57 am
    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

  50. Written by mike on March 31, 2011 at 5:16 am
    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?

Subscribe to comments via RSS

Leave a Reply