Reading Google Analytics data from PHP


Google Analytics has become a important part of any web sites traffic analysis strategy. And with the release of the Analytics API people have been able to create custom reports and mashups for their organizations. Although no standard library is available from Google for PHP, some small and easy interfaces are available out there. In this post we will see how to access Google Analytics data using PHP using the GAPI library.

Installing the GAPI class

The following code uses the GAPI – Google Analytics API PHP Interface to help us access the Analytics data. So before proceeding you need to download the class file from the GAPI home.

Dimensions & Metrics

Before we start a small primer on Google Analytics Dimensions & Metrics will be helpful.

What is a dimension?
Dimensions are things like browser and country, browser versions, landing and exit pages, the URL of a page, and the source website a visitor has come from.
Google Analytics uses the following 5 main marketing dimensions for analysis:

* Source
* Medium
* Term
* Content
* Campaign

What is a metric?
Metrics are the quantitative measure of a dimension for specific data types, such as counts of new visitors, page views, unique page views etc.

Getting the Google Analytics data

Now that we have seen what Dimensions & Metrics are we will proceed with an example. In this example we will fetch the ‘source’ dimension, which shows the source website the visitor is coming from and the ‘visits’ metric. This tells us how many visitors are coming from a particular source to our site.

<?php
 
require 'gapi-1.3/gapi.class.php';
 
/* Set your Google Analytics credentials */
define('ga_account'     ,'YOUR ANALYTICS EMAIL');
define('ga_password'    ,'YOUR ANALYTICS PASSWORD');
define('ga_profile_id'  ,'ANALYTICS SITE PROFILE ID');
 
$ga = new gapi(ga_account,ga_password);
 
/* We are using the 'source' dimension and the 'visits' metrics */
$dimensions = array('source');
$metrics    = array('visits');
 
/* We will sort the result be desending order of visits, 
    and hence the '-' sign before the 'visits' string */
$ga->requestReportData(ga_profile_id, $dimensions, $metrics,'-visits');
 
$gaResults = $ga->getResults();
 
$i=1;
 
foreach($gaResults as $result)
{
    printf("%-4d %-40s %5d\n",
           $i++,
           $result->getSource(),
           $result->getVisits());
}
 
echo "\n-----------------------------------------\n";
echo "Total Results : {$ga->getTotalResults()}";    
 
?>

Below I’ve listed the top ten results of the output.

No.  Source                                   Visits
------------------------------------------------------
1    google                                   10549
2    (direct)                                  1484
3    stumbleupon.com                           1338
4    webintenta.com                             159
5    bing                                       142
6    yahoo                                      115
7    feedburner                                  97
8    phpdeveloper.org                            70
9    t3n.de                                      64
10   clearspace.openqa.org                       43

As you can see the main method in the class is the ‘requestReportData()’, which has the following structure:

function requestReportData($report_id,      
                           $dimensions, 
                           $metrics, 
                           $sort_metric=null, 
                           $filter=null, 
                           $start_date=null, 
                           $end_date=null, 
                           $start_index=1, 
                           $max_results=30)

You can get the Dimension and Metric result by prefixing ‘get’ to the dimension or metric name. For e.g, if you metric name is ‘region’, you can get the result by using:

$result->getRegion();

Although I have only provided a single Dimension and Metric in the example code, the $dimensions and $metrics parameter can take multiple parameters as shown below:

$dimensions = array('source', 'region');
$metrics    = array('visits');

Bear in mind to specify a valid ‘dimension-metric’ combination as given in the API Docs. Specifying an invalid combination will return 0 results.

The output after adding the ‘region’ dimension is shown below.

No. Source     Region               Visits
-----------------------------------------
1   google     (not set)              965
2   google     England                796
3   google     California             650
4   google     Maharashtra            343
5   google     Karnataka              340
6   google     Tamil Nadu             295
7   google     New York               225
8   google     Andhra Pradesh         189
9   google     Texas                  172
10  google     Ontario                165

Modifying the amount of results returned

By default the class returns the first 30 results, although the raw Google API returns 1000 results by default. You can increase the same by changing the $max_results parameter. Google Analytics returns a maximum of 10,000 results, even if you set the $max_results parameter above 10,000. To get the results above that limit you need to set the $start_index parameter to 10,000, which will then get the results starting at 10,000.

$ga->requestReportData(ga_profile_id,
                       $dimensions,
                       $metrics,
                       '-visits', // Sort by 'visits' in descending order
                       '','','', // We are not using this paras yet
                       1,  // Start Index
                       500 // Max results
                       );

You can get the total number of results by using the getTotalResults() method. This can be helpful in pagination.

$ga->getTotalResults();

Setting the Google Analytics report period

By default the class returns the data for the last 1 month from today if no report period is specified. You can specify the report period as below. The date format is in the form ‘YYYY-MM-DD’.

$ga->requestReportData(ga_profile_id,
                       $dimensions,
                       $metrics,
                       '-visits', // Sort by 'visits' in descending order
                       '',
                       '2009-10-01', // Start Date
                       '2009-12-31', // End Date
                       1,  // Start Index
                       500 // Max results
                       );

Filtering the data

You can further filter the results using the $filter parameter. Filtering is a little tricky, so be sure to read the Google documentation.

$filter = 'country == United States';
 
$ga->requestReportData(ga_profile_id,
                       $dimensions,
                       $metrics,
                       '-visits', // Sort by 'visits' in descending order
                       $filter, // Filter the data
                       '2009-10-01', // Start Date
                       '2009-12-31', // End Date
                       1,  // Start Index
                       500 // Max results
                       );

You can also combine various options:

$filter = 'country == United States && visitorType == New Visitor';
// OR
$filter = 'country == United States &&
           visitorType == New Visitor &&
           browser == Firefox';

Getting a list of your Google Analytics Accounts

Most users have more than one profiles in their Analytics account. You can easily get a list of all your accounts (sitename – profileid) with the following code.

<?php
 
require 'gapi-1.3/gapi.class.php';
 
/* Set your Google Analytics credentials */
define('ga_account'     ,'YOUR ANALYTICS EMAIL');
define('ga_password'    ,'YOUR ANALYTICS PASSWORD');
 
$ga = new gapi(ga_account,ga_password);
 
$gaResult = $ga->requestAccountData();
 
foreach($gaResult as $result)
{
  printf("%-30s %15d\n", $result, $result->getProfileId());
}
 
?>

With this we conclude this post. It will be quite helpful if you go over the below references if you are unfamiliar with the Google Analytics API.

Update

Webresourcesdepot features a nifty little application using the above to dispay the Google pageviews in a Feed-burner style chicklet display.

References:
a. Google Analytics Data API – Data Feed
b. Dimensions & Metrics Reference
c. Filters

This site is a digital habitat of Sameer Borate, a freelance web developer working in PHP, MySQL and WordPress. I also provide web scraping services, website design and development and integration of various Open Source API's. Contact me at metapix[at]gmail.com for any new project requirements and price quotes.

31 Responses

1

Jonas

February 2nd, 2010 at 3:18 am

Very good tutorial :) Can I translate it into French for my blog (xoodeo.com) ?

sameer

February 2nd, 2010 at 3:32 am

You are welcome to translate, Jonas!

3

Jonas

February 2nd, 2010 at 3:36 am

Nice, thanks a lot ! :)

4

uberVU - social comments

February 2nd, 2010 at 4:20 am

Social comments and analytics for this post…

This post was mentioned on Twitter by stepanov: Reading Google Analytics data from PHP http://bit.ly/duVxil

5

Alexsandro

February 9th, 2010 at 12:28 pm

Very good code, I find for it…! :) thanks for share.

6

Really Useful Tutorials You Should Have Read in February 2010 Ajax Help W3C Tag

March 4th, 2010 at 9:08 pm

[...] Reading Google Analytics data from PHP By Sameer Borate, February 1st, 2010 Site: Code Diesel [...]

7

Anil Kumar Panigrahi

March 25th, 2010 at 3:52 am

Hi,

Thank you for sharing good code, i am already implemented retrieve google analytics code visits for inkakinada.com site with another code, but it is quite simple that code.

Thank you.

8

poison

April 27th, 2010 at 9:25 pm

Hi Sameer, it seems great, but it just does not work for me. After I
installed GAPI, all the php pages return a blank page.

I am using PHP 5.2.6, the settings for CURL and openSSL are:
cURL support: enabled
cURL Information: libcurl/7.15.5 OpenSSL/0.9.8b zlib/1.2.3 libidn/0.6.5
OpenSSL support: enabled
OpenSSL Version: OpenSSL 0.9.8b 04 May 2006

I checked the http response and found that there is a 500 error. Do you have any ideas on this? Thank you.

sameer

April 27th, 2010 at 9:54 pm

500 is a general ‘catch-all’ error generated by the Web server. Are you running it on your localhost or a online server? I cannot really pinpoint the problem as there can be many issues, but you can get the error details from your Apache logs.

10

deepak

May 19th, 2010 at 4:40 pm

11

web development

June 7th, 2010 at 11:46 pm

do you have complete list of dimensions and metrics also what are the available results ($result->getProfileId())?

12

deltacubed web design

June 22nd, 2010 at 3:10 am

Great article, thanks – just what I was looking for. I’ve only just started playing around with this API but it seems pretty powerful for some management reports I’m putting together at the moment.

13

Vrashank

June 23rd, 2010 at 3:48 am

Fantastic! Just what I was looking for, how to get top ten results…I think i can use this with Visualisation as well…
cheers!

14

Guilherme

August 12th, 2010 at 11:35 am

http://www.granasblog.blogspot.com

Is fantastic, I make it for create a graph using PHPLot. Very well.

15

Webdesign

October 14th, 2010 at 8:08 am

Amazing, going to make my first tool later to day.
Love it so far thanks!!!!!

16

Henrik

November 3rd, 2010 at 3:05 am

Tnx for this excellent explanation. Now I understand how to use metrix and filters. I do plan to use this for a simple dashboard page for our companys many webbsites

17

Acceder a Google Analytics con PHP | code

December 10th, 2010 at 3:37 am

[...] a Google Analytics con PHP En CodeDiesel he encontrado un artículo titulado: Reading Google Analytics data from PHP en el que nos explican como acceder a los datos de Google Analytics utilizando [...]

18

Abhilash

January 19th, 2011 at 10:53 am

Hi..

Firstly, a great article.. Works good for me..

Checking onto see if you have built a version that takes in segments as an input parameter for requestReportData function.. The reason I need this is that I need to track mobile traffic.

Let me know what your thoughts are..

Thanks!

19

abel

August 27th, 2012 at 11:00 pm

Fatal error: Uncaught exception ‘Exception’ with message ‘GAPI: Failed to request account data. Error: ” Error 404 (Not Found)!!1 *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}} 404. That’s an error. The requested URL /analytics/feeds/accounts/default?start-index=1&max-results=20 was not found on this server. That’s all we know. “‘ in E:\www\test\a\gapi.class.php:92 Stack trace: #0 E:\www\test\a\index.php(24): gapi->requestAccountData() #1 {main} thrown in E:\www\test\a\gapi.class.php on line 92
thanks

20

tprevet

September 1st, 2012 at 8:28 am

abel
I have the same probleme since august…
Maybe a google update

21

thomas prevet

September 1st, 2012 at 9:39 am

abel,

Google change authentication, you can see the solution there :

http://code.google.com/p/gapi-google-analytics-php-interface/issues/detail?id=84

22

Jaco

September 16th, 2012 at 3:46 pm

Anyone found a soluttion for this problem? the links as soluttions posted above doesnt work anymore

Fatal error: Uncaught exception ‘Exception’ with message ‘GAPI: Failed to request account data. Error: ” Error 404 (Not Found)!!1 *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}

23

Rock

October 16th, 2012 at 1:05 am

I can`t found getTotalResults this method.

24

Rock

October 16th, 2012 at 2:30 am

I found this can be fix “getTotalResults”

http://bbs.7bicycle.com/thread-8-1-1.html

25

Harsh

November 15th, 2012 at 1:35 am

As per your top ten results of the output. Suppose if I want to print only (direct) visits so what i can do ??

26

Acceder a Google Analytics con PHP « code

April 10th, 2013 at 3:04 pm

[...] CodeDiesel he encontrado un artículo titulado: Reading Google Analytics data from PHP en el que nos explican como acceder a los datos de Google Analytics utilizando [...]

27

Felipe Furlan

May 14th, 2014 at 7:15 am

congratulations! i did….

but how i can group the values ?

28

Felipe Furlan

May 19th, 2014 at 5:03 am

hey, i can get the sex, age and O.S datas ?

29

ram

May 26th, 2014 at 10:19 pm

Hi,

Warning: require(gapi-1.3/gapi.class.php) [function.require]: failed to open stream: No such file or directory in.

i’m not getting what is the problem.

plz help me

30

Jane

May 30th, 2014 at 4:32 pm

My getResults() returns an empty array for me. Does anyone have insight on this? Thank you so much!

31

Husnain

July 15th, 2014 at 12:56 am

how can I get visitor for a specific sites?can we put website as a filter?
I want to get visitors for given site?

Your thoughts

Sign up for fresh content in your email