Skip to the content...

Welcome to the David Walsh Blog. I'm a MooTools, Dojo, jQuery, CSS, and PHP Web Developer located in Madison, Wisconsin, United States. Please contact me if I can make your experience on my website better.

Retrieve Google Analytics Visits and PageViews with PHP

47 Responses »

Google Analytics is an outstanding website analytics tool that gives you way more information about your website than you probably need. Better to get more than you want than not enough, right? Anyways I check my website statistics more often than I should and it ends up taking a few minutes to get logged in, select the right site, select the current day, etc. I found a great Google Analytics PHP API that allows me to get just the statistics I'm looking for.

The PHP Library

The PHP class I found, analytics, can be downloaded at http://www.swis.nl/ga/. The site also gives a few solid examples.

The PHP

//session_start for caching, if desired
session_start();
//get the class
require 'ga/analytics.class.php';
//sign in and grab profile
$analytics = new analytics('david@davidwalsh.name', 'myP@ssw0rd');
$analytics->setProfileByName('davidwalsh.name');
//set the date range for which I want stats for (could also be $analytics->setDateRange('YYYY-MM-DD', 'YYYY-MM-DD'))
$analytics->setMonth(date('n'), date('Y'));
//get array of visitors by day
print_r($analytics->getVisitors());
//get array of pageviews by day
print_r($analytics->getPageviews());

As you'd expect, we first grab the class and immediately sign providing your credentials and website profile (you can just use your domain). Once authenticated we set a date range and retrieve our visitors and pageviews.

The Sample PHP Results

The above code retrieved visits and pageviews for the current month. What's returned is an array that looks as follows:

Array
(
    [01] => 6539
    [02] => 6677
    [03] => 6160
    [04] => 5563
    [05] => 2964
    [06] => 2973
    [07] => 5080
    [08] => 6078
    [09] => 5927
    [10] => 6177
	...
)

A very simple array numbered by day. You could do anything you wanted with the array -- create averages, peaks, lows, etc.

Advanced Usage

The analytics class also allows you to retrieve search keywords and anything else you might like:

$keywords = $analytics->getData(array(
						'dimensions' => 'ga:keyword',
		                'metrics' => 'ga:visits',
		                'sort' => 'ga:keyword'
						)
					);

The PHP analytics class is a masterpiece. Rest assured I'll be doing a ton of work with this class for customers and my own websites! Do you have any ideas as to what you could use this class for? Share!

Discussion

  1. simon
    September 29, 2009 @ 8:29 am

    I already tried some classes to retrive GA data but they were all veeeeery slow ! It sometimes took more than 5 minutes to retrieve the data for last year… Is this one faster ? Would be great to have a usable GA class !

  2. mlazz
    September 29, 2009 @ 8:32 am

    Thanks for this most useful information David.

    I’m working on a project that needs to retreive data from GA. You just saved me from searching for this myself ;)

  3. September 29, 2009 @ 8:33 am

    @Simon: Check out the demo — super fast for me.

  4. September 29, 2009 @ 9:01 am

    Is there anyway to grab some of the flash movies on the GA page? I would love to add that directly to my cms…

  5. September 29, 2009 @ 9:20 am

    @Simon must be the connection between you and Google… or maybe the proxy in between…

  6. September 29, 2009 @ 10:02 am

    Great. Thank you for sharing David.

  7. September 29, 2009 @ 10:35 am

    Thanks for Sharing David. I’ve test some others but this one looks perfect. I’ll try to use it in a seo project next time. Seems like to save much time with this ;)

    Greets from Germany

  8. September 29, 2009 @ 10:48 am

    I use a customized Piwik dist. No need to bother with the google monopoly :p

  9. September 29, 2009 @ 12:50 pm

    Right on, Mr. Walsh. I guess I’m going to have to show how to do this in Python ;)

  10. September 29, 2009 @ 1:11 pm

    I think there is a wordpress plugin that does something like this too. It’s pretty clever.

  11. September 29, 2009 @ 1:28 pm

    Thanks for that! Will be needing this in some future projects.

  12. September 29, 2009 @ 1:28 pm

    For WordPress sites like this one, if you wanted to view simple stats like this, wouldn’t it be just as good to view WordPress Stats in the admin panel? Or is that not that accurate? That’s what I’ve been doing.

    And then if you do want detailed ones, you could log into Analytics.

  13. September 29, 2009 @ 4:41 pm

    Nice article David. I haven’t really looked into it yet, but this looks really easy to implement. Thanks alot for writing it down :)

  14. September 29, 2009 @ 5:02 pm

    Thanks! When you’ve linked your Analytics and AdSense-accounts, you can also do some nice things with your AdSense-statistics :)

  15. September 29, 2009 @ 6:37 pm

    We are looking into implementing Alfresco eCMS in our organisation, with a php web frontend for our web content, this now means we might be able to pull all that analytical goodness right into our workflows and get document and item level stats, which is awesome!

  16. September 29, 2009 @ 7:17 pm

    @Adriaan: No idea but I’d bet there’s already some sort of graphing library for Flash to get you started.

  17. September 29, 2009 @ 7:39 pm

    @Eric Wendelin: Let’s see it!

  18. laurie
    September 29, 2009 @ 10:58 pm

    This is great!

    I came across a (free) Flash based charting php class and cooked up some great charts using this API. Here’s a link for anyone interested: http://www.fusioncharts.com/free/

  19. simon
    September 30, 2009 @ 5:20 am

    @David: Yes the demo is fast, but you didn’t request much data ;) What would happen if you wanted a table with the numer of visits for each months of the year + another table with the number of pageviews for each months of the year. Because in my opinion this sort of classes are usefull if you want to ‘export’ your reports from the google analytics page into your CMS. And to do so you need to export a lot of data, which could slow things down…

    Oh and @Laurie, fusionchart is indeed great !

  20. floris
    September 30, 2009 @ 7:19 am

    This was created by my former boss. It is indeed a great class and it’s great you write about it!

  21. September 30, 2009 @ 7:20 am

    @Simon: Cache the information you retrieve from past dates — that never changes.

  22. simon
    September 30, 2009 @ 7:44 am

    Yeah, I guess that’s the only real solution. Thanks anyway :)

  23. September 30, 2009 @ 8:06 am

    @david : thanks for your class : it’s great and very simple to implement.

    I’ve just improved dimensions on getVisitors() and getPageView() :
    -> you request ga:day and as I need to use date range, this method only returns days num and overwrite datas if you request more than one month

    –> I’ve modified this with “ga:date” on dimension and sort. As this, my returns are “20090930″ instead of “30″ and datas are not overrited.

    So I can suggest to you to change the code source with this improvement :)

    bye and another time : big thanks !

  24. September 30, 2009 @ 12:00 pm

    That’s awesome. A nice quick way to see some stats without having to login. Thanks David.

  25. October 2, 2009 @ 4:39 am

    You should check out ga:pi(), I really found that more useful than the class you are linking to here.

    http://code.google.com/p/gapi-google-analytics-php-interface/

  26. lossendae
    October 3, 2009 @ 4:18 pm

    I’ve tried the class on local, and it did not work until i added one line for CURL.

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

    above the following line:

    curl_setopt($rRequest, CURLOPT_RETURNTRANSFER, 1);

    Don’t know if it is caused by wamp or the local environment.

  27. lossendae
    October 4, 2009 @ 1:03 pm

    Well, ive finally gone into the gapi class that we can find on googlecode and it is better in many way!

  28. October 6, 2009 @ 2:02 am

    Thanks David for your useful API.

  29. tanya
    October 22, 2009 @ 7:44 am

    I am using GA and I am at the page views…from here I do not know how to get the links of page views

  30. paulo
    October 23, 2009 @ 8:17 am

    Nice tut!

    Could you write another one with ga:pi() and jQuery ?

    Good work

  31. October 23, 2009 @ 8:18 am

    @Paulo: What’s ga:pi() ?

  32. paulo
    October 23, 2009 @ 8:21 am

    @David Walsh: It’s gapi-google-analytics-php-interface

    http://code.google.com/p/gapi-google-analytics-php-interface/

  33. October 23, 2009 @ 8:40 am

    … and ga:pi() seems alot more useful than http://www.swis.nl/ga/, as mentioned earlier :)

  34. paulo
    October 23, 2009 @ 9:15 am

    @Torkil Johnsen: I’ve done it myself :)

  35. October 23, 2009 @ 12:21 pm

    I have too, works like a charm

  36. victor
    October 26, 2009 @ 12:04 pm

    Does anyone have an example of a fully functional ga:pi() code?

    David: this is great. Question: can this be configured to pull multiple metrics from several profiles at a time?

  37. October 26, 2009 @ 12:47 pm

    /* ga:pi() example that displays pageviews, visits and time on page for the current pagetitle. The results are grouped by years, from 2007->now.

    Only variable in here you have to look out for is $currentPageTitle. This is the current page’s title, which I fetch from Joomla CMS. */

    require_once ‘gapi.class.php’;

    $ga_user = ‘yourmail@example.com’;
    $ga_pass = ‘yourpassword’;
    $ga_siteId = 123456789; // insert your siteId
    $ga_startDate = ’2007-01-01′; // I want data from 2007
    $ga_endDate = date(‘Y-m-d’); // … until now

    $ga = new gapi($ga_user,$ga_pass,isset($_SESSION['ga_auth_token'])?$_SESSION['ga_auth_token']:null);
    $_SESSION['ga_auth_token'] = $ga->getAuthToken();
    $ga_filter = ‘pageTitle == ‘.$currentPageTitle; // fetch stats for the current page
    $ga->requestReportData($ga_siteId,’year’,array(‘pageviews’, ‘visits’, ‘timeOnPage’), ‘year’, $ga_filter, $ga_startDate, $ga_endDate);

    $results = $ga->getResults();

    print_r($results);

  38. victor
    October 26, 2009 @ 12:54 pm

    Torkil:

    thanks for the speedy response. I am looking to configure this to pull a couple of metrics ( say visits / visitors / pageviews ) from several profiles ( my company has multiple profiles setup). ANy ideas how?

  39. October 26, 2009 @ 1:59 pm

    I can’t do the job for you man. Example is there, the link to ga:pi() is there, time to get to work yourself… ;)

  40. victor
    October 26, 2009 @ 2:04 pm

    a thousand apologies – I dont know php at all, hence my question. You are right, got to start somewhere. thanks

  41. October 26, 2009 @ 2:30 pm

    Sorry then, no knowledge of PHP will make this tough for you, unless you know some other programming language. Still; Give a man a fish, and you feed him for a day. Teach a man to fish, and you feed him for a lifetime. – Lao Tzu.

    If you plan on using PHP for other things than to just fetch the some statistics once, it will be well worth looking into. For a beginner it is also an easy language to start up with.

  42. cent
    November 21, 2009 @ 1:53 am

    I haven’t studied the GA API yet, but could you also get a list of referrer urls to your site for a specific day and grab that information for processing on the server side?

  43. November 21, 2009 @ 7:37 am

    Sounds like you should take a couple of minutes to study both ga:pi() and the Analytics API. I think that if Google Analytics allows it, ga:pi() is able to fetch it.

    http://code.google.com/intl/nb/apis/analytics/docs/gdata/gdataDeveloperGuide.html

  44. February 5, 2010 @ 7:53 pm

    For those of you not as technical, I have been working on a free service which allows publishers to embed reports and graphs based on their Google Analytics data directly into their own website. It requires absolutely no programming. The site is:

    http://www.embeddedanalytics.com

  45. sanjoy
    June 3, 2010 @ 6:00 am

    I have downloaded the code and run on my system. But it is not running.
    Can anyone tell me why this is happining.

  46. anonymice
    July 5, 2010 @ 2:05 am

    Hello,

    With ga:pi() can anyone tell me how to implement the chart that can be seen in google analytics account itself?

    Also I wanna show that map which shows coutry based visits/visitors.

    Any help would be really appreciated.

    Thanks

  47. July 18, 2010 @ 12:38 am

    Nice class, but users should note that there are two flaws with the getVisitors method.

    #1 as Guiltouf notes, the dimensions use ‘day’ as opposed to ‘date’ so results containing more than one month get overridden

    #2 The metric used is ‘visits’ instead of ‘visitors’ and thus won’t match the GA dashboard

    Changing these two parameters makes the report work fine

Be Heard!

Share your thoughts with fellow developers of all skill levels! I want to hear from you!

Name*:
Email*:
Website:  
Wrap your code with <code> tags, f00!