Retrieve Google Analytics Visits and PageViews with PHP

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!


Comments

  1. Simon

    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

    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. David Walsh

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

  4. Adriaan

    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. Thomas Hambach

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

  6. Can Berkol

    Great. Thank you for sharing David.

  7. Daniel

    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. Alex

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

  9. Eric Wendelin

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

  10. Ryan Rampersad

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

  11. Gareth Poole

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

  12. James Lin

    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. GP

    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. Yannick Jorna

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

  15. Paul M

    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. David Walsh

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

  17. David Walsh

    @Eric Wendelin: Let’s see it!

  18. Laurie

    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

    @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

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

  21. David Walsh

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

  22. Simon

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

  23. Guiltouf

    @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. Jonathan Bennett

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

  25. Torkil Johnsen

    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

    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

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

  28. Pramod Poudel

    Thanks David for your useful API.

  29. tanya

    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

    Nice tut!

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

    Good work

  31. David Walsh

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

  32. Paulo

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

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

  33. Torkil Johnsen

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

  34. Paulo

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

  35. Torkil Johnsen

    I have too, works like a charm

  36. Victor

    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. Torkil Johnsen

    /* 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

    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. Torkil Johnsen

    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

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

  41. Torkil Johnsen

    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

    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. Torkil Johnsen

    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. Mark Schenkel

    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

    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

    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. Ben

    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

  48. David LeBlanc

    Add this two lines after line 351 :
    curl_setopt ($rRequest, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt ($rRequest, CURLOPT_SSL_VERIFYPEER, 0);
    it solve many problem on wamp and easyphp

  49. Zamshed Farhan

    Uuuhhhh…. great. I m searching for it for a long time.

  50. masoud

    Hi
    I wanna show my ga infos in my sidebar.
    What should I do exactly?
    Where do i have to copy the codes?
    Help me

  51. hary

    good php class for GA, thanks lot

  52. Kevin Z

    Is anyone else having issues with this now that Google has upgraded Analytics. Any ideas on the fixes? I assume it is not me because even the demo page displays a blank page. Any thoughts?

    Thanks!


Be Heard!

Share your thoughts without being a jerk! And wrap your code in <code> tags, f00!

Name*:
Email*:
Website: