Retrieve Google Analytics Visits and PageViews with PHP

By  on  

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!

Recent Features

  • By
    Convert XML to JSON with JavaScript

    If you follow me on Twitter, you know that I've been working on a super top secret mobile application using Appcelerator Titanium.  The experience has been great:  using JavaScript to create easy to write, easy to test, native mobile apps has been fun.  My...

  • By
    JavaScript Promise API

    While synchronous code is easier to follow and debug, async is generally better for performance and flexibility. Why "hold up the show" when you can trigger numerous requests at once and then handle them when each is ready?  Promises are becoming a big part of the JavaScript world...

Incredible Demos

  • By
    Implementing Basic and Fancy Show/Hide in MooTools 1.2

    One of the great parts of MooTools is that the library itself allows for maximum flexibility within its provided classes. You can see evidence of this in the "Class" class' implement method. Using the implement method, you can add your own methods to...

  • By
    dwImageProtector Plugin for jQuery

    I've always been curious about the jQuery JavaScript library. jQuery has captured the hearts of web designers and developers everywhere and I've always wondered why. I've been told it's easy, which is probably why designers were so quick to adopt it NOT that designers...

Discussion

  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. @Simon: Check out the demo — super fast for me.

  4. 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. @Simon must be the connection between you and Google… or maybe the proxy in between…

  6. Great. Thank you for sharing David.

  7. 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. I use a customized Piwik dist. No need to bother with the google monopoly :p

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

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

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

  12. 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. 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. Thanks! When you’ve linked your Analytics and AdSense-accounts, you can also do some nice things with your AdSense-statistics :)

  15. 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. @Adriaan: No idea but I’d bet there’s already some sort of graphing library for Flash to get you started.

  17. @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. @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. @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. That’s awesome. A nice quick way to see some stats without having to login. Thanks David.

  25. 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. 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. @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. … 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. 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. /* 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. 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. 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. 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. 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. 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. Uuuhhhh…. great. I m searching for it for a long time.

  50. 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. good php class for GA, thanks lot

  52. 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!

  53. RC

    how to retrieved page name and visit using api downloaded from http://www.swis.nl/ga/.

  54. kiruba

    Hi guys, For past one year i am using GAPI. No issues. But suddenly i got “GAPI: Failed to authenticate user. Error: “”. In local environment works fine. but in cloud not working. i checked the code everything is right. Is their any way google locked my IP(server). I checked with other (IP)server its working. Please help…

  55. Dude you saved my job, I’ve been working on getting analytic data for over a week now. My boss was looking at me like I need to finish soon. Now that I have been passed the difficult way of authenticating to get the data. I can move on to more fun things.

    Thanks,

  56. HI David,

    I am working on integrating the google analytics api for keyword searching which will fetch the all related data as searches, local searches.

    But could not find proper way for such api integration and documentation on google is complecated and confusing.

    can you pls help me out? I m waiting for your reply. Pls understand its urgent.

    Thanks in advance.

  57. Also could not find any PHP class files on http://www.swis.nl/ga/ as per your post and demo link is blank result.

    If you could mail me the files or could locate to any another location it would be great help.

    Thanks.

  58. nate

    hey guys,
    there were changes to google analytics recently.
    this class doesnt work anymore…
    @david, do u have a fix for this?

  59. Hello everyone, for the recent update made to the Google Analytic this code won’t work, you have to modify the link that is making the request, that’s all. Is an easy fix but you could run into complications if you don’t know the code. I had to do it for work, so when it didn’t work, I had to fix it. Mine is fix all I had to do was to change the link that makes the requests. Read the error you get you’ll see what I am talking about and the line where the problem is, if not, shoot me an email, I’ll be more than happy to help.

    Thanks,

    -Hernando Cadet.

    • nate

      hi Hernando,
      can u please post the new request link?
      i could not find what it should be now..

  60. Jabran

    Hi. I’d like to know if this library can be used to access CUSTOM VARIABLES??

    Please let me know how.

    Thanks.

  61. I am working in a similar project and need to this. Yours is an excellent post to my library. Thanks a lot for sharing.

  62. jen

    I’m new so don’t bite me, but doesn’t this method make your username and password public?

  63. jen

    I’m struggling at the moment, trying to figure out if I can retrieve the pageviews of one website to send to another website (api?). I’m wondering if I can grab the ‘the_views’ data from the “WP Pageviews” plugin using JSON API plugin somehow…

    *scratches head and sighs*

  64. The better way to fetch google analytics data in php is by using the google client api

    https://code.google.com/p/google-api-php-client/

  65. how can i get total count of new visitors and returning visitors country n region wise in php

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!