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.
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.
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
Very good tutorial ๐ Can I translate it into French for my blog (xoodeo.com) ?
You are welcome to translate, Jonas!
Nice, thanks a lot ! ๐
Very good code, I find for it…! ๐ thanks for share.
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.
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.
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.
very good tutorial
http://maps.google.co.in/maps?hl=en&q=virginsoftware.net&um=1&ie=UTF-8&sa=N&tab=wl
do you have complete list of dimensions and metrics also what are the available results ($result->getProfileId())?
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.
Fantastic! Just what I was looking for, how to get top ten results…I think i can use this with Visualisation as well…
cheers!
http://www.granasblog.blogspot.com
Is fantastic, I make it for create a graph using PHPLot. Very well.
Amazing, going to make my first tool later to day.
Love it so far thanks!!!!!
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
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!
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
abel
I have the same probleme since august…
Maybe a google update
abel,
Google change authentication, you can see the solution there :
http://code.google.com/p/gapi-google-analytics-php-interface/issues/detail?id=84
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}
I can`t found getTotalResults this method.
I found this can be fix “getTotalResults”
http://bbs.7bicycle.com/thread-8-1-1.html
As per your top ten results of the output. Suppose if I want to print only (direct) visits so what i can do ??
congratulations! i did….
but how i can group the values ?
hey, i can get the sex, age and O.S datas ?
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
My getResults() returns an empty array for me. Does anyone have insight on this? Thank you so much!
how can I get visitor for a specific sites?can we put website as a filter?
I want to get visitors for given site?
Got this error-
Fatal error: Uncaught exception ‘Exception’ with message ‘GAPI: Failed to authenticate user. Error: “”‘ in /var/tools/gapi.class.php:418 Stack trace: #0 /var/www/RPT-145/tools/gapi.class.php(62): gapi->authenticateUser(‘abc@gmail…’, ‘@abc123@123@’) #1 /var/transaction_report.php(37): gapi->__construct(‘abc@gmail…’, ‘@abc123@123@’) #2 {main} thrown in /var/tools/gapi.class.php on line 418
Please help me to solve this
thanks in advance ๐
Good Code
It’s working fine.
Still I want bounce rate so can i help me?
Got this error:
Fatal error: Uncaught exception ‘Exception’ with message ‘GAPI: Failed to authenticate user. Error: “Error=BadAuthentication “‘ in /home/content/63/9126263/html/GAPI/gapi.class.php:418 Stack trace: #0 /home/content/63/9126263/html/GAPI/gapi.class.php(62): gapi->authenticateUser(‘arti.debut@gmai…’, ‘password!123’) #1 /home/content/63/9126263/html/GAPI/index.php(10): gapi->__construct(‘arti.debut@gmai…’, ‘password!123’) #2 {main} thrown in /home/content/63/9126263/html/GAPI/gapi.class.php on line 418
Please help me.
Fatal error: Uncaught exception ‘Exception’ with message ‘GAPI: Failed to authenticate user. Error: “Error=BadAuthentication Url=https://www.google.com/accounts/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbtE4WpujskeTc0Vw3cEhb8AePOuwSdfRW109GJeZenXIxh4bchjLDiULXSqBH5EVzl080zokF4C7GMxc-sQamzIZEDdUAEPmJG_lnNHtNO4fKiwJiMP0dL-IbgiPGXxOLAMj3vSJl-9scMZQwZToUP8tJrLD0mqudenEKZXa5sHntSbFEV1oeufoPi2Z4DC9Kf3qjcKHxpv-sqVZc-qj-tr2DCJ5A Info=WebLoginRequired “‘ in C:\xampp\htdocs\Lahiru\gapi.class.php:418 Stack trace: #0 C:\xampp\htdocs\Lahiru\gapi.class.php(62): gapi-C:\xampp\htdocs\Lahiru\gapi.class.php on line 418
please give me any idea to solve this ….