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.
//session_start for caching, if desired session_start(); //get the class require 'ga/analytics.class.php'; //sign in and grab profile $analytics = new analytics('email@example.com', '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 (  => 6539  => 6677  => 6160  => 5563  => 2964  => 2973  => 5080  => 6078  => 5927  => 6177 ... )
A very simple array numbered by day. You could do anything you wanted with the array -- create averages, peaks, lows, etc.
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!
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 !
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 ;)
@Simon: Check out the demo — super fast for me.
Is there anyway to grab some of the flash movies on the GA page? I would love to add that directly to my cms…
@Simon must be the connection between you and Google… or maybe the proxy in between…
Great. Thank you for sharing David.
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
I use a customized Piwik dist. No need to bother with the google monopoly :p
Right on, Mr. Walsh. I guess I’m going to have to show how to do this in Python ;)
I think there is a wordpress plugin that does something like this too. It’s pretty clever.
Thanks for that! Will be needing this in some future projects.
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.
Nice article David. I haven’t really looked into it yet, but this looks really easy to implement. Thanks alot for writing it down :)
Thanks! When you’ve linked your Analytics and AdSense-accounts, you can also do some nice things with your AdSense-statistics :)
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!
@Adriaan: No idea but I’d bet there’s already some sort of graphing library for Flash to get you started.
@Eric Wendelin: Let’s see it!
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/
@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 !
This was created by my former boss. It is indeed a great class and it’s great you write about it!
@Simon: Cache the information you retrieve from past dates — that never changes.
Yeah, I guess that’s the only real solution. Thanks anyway :)
@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 !
That’s awesome. A nice quick way to see some stats without having to login. Thanks David.
You should check out ga:pi(), I really found that more useful than the class you are linking to here.
I’ve tried the class on local, and it did not work until i added one line for CURL.
above the following line:
Don’t know if it is caused by wamp or the local environment.
Well, ive finally gone into the gapi class that we can find on googlecode and it is better in many way!
Thanks David for your useful API.
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
Could you write another one with ga:pi() and jQuery ?
@Paulo: What’s ga:pi() ?
@David Walsh: It’s gapi-google-analytics-php-interface
… and ga:pi() seems alot more useful than http://www.swis.nl/ga/, as mentioned earlier :)
@Torkil Johnsen: I’ve done it myself :)
I have too, works like a charm
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?
/* 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. */
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?
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… ;)
a thousand apologies – I dont know php at all, hence my question. You are right, got to start somewhere. thanks
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.
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?
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.
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:
I have downloaded the code and run on my system. But it is not running.
Can anyone tell me why this is happining.
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.
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
Add this two lines after line 351 :
it solve many problem on wamp and easyphp
Uuuhhhh…. great. I m searching for it for a long time.
I receive a 400 error:
Caught exception: Bad request (400) url: https://www.google.com/analytics/feeds/data?ids=13126318&start-date=2011-01-01&end-date=2011-01-31&dimensions=ga:day&metrics=ga:visits&sort=ga:day
I wanna show my ga infos in my sidebar.
What should I do exactly?
Where do i have to copy the codes?
good php class for GA, thanks lot
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?
how to retrieved page name and visit using api downloaded from http://www.swis.nl/ga/.
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…
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.
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.
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.
there were changes to google analytics recently.
this class doesnt work anymore…
@david, do u have a fix for this?
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.