/* PHP & MySQL Journal */
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.
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.
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.
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 |
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(); |
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 ); |
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'; |
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.
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, a freelance web developer working from Pune.More
6 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 [...]