Google Analytics (GA) is the de facto solution for analyzing web site traffic and trends. Millions of users around the globe rely on GA for determining not only what web site content is resonating with visitors, but also how visitors came to arrive at the web site,
each visitor's geographical location, their operating system and browser, and
much more. If you're not regularly relying upon Google Analytics or a similarly
capable analytical service, then you're left at a major competitive disadvantage
in terms of your ability to effectively understand the interests, demographics,
and technical requirements of your audience.
Yet logging into GA daily can be a tedious task. Faced with countless other work-related demands, adding even one more requirement can be overwhelming. Further, although you can configure GA to send formatted
reports via email on a daily, weekly, monthly, and quarterly basis (see
Figure
1), sometimes you're just interested in quickly gaining a bird's eye view of key
statistics, such as the current number of daily visitors and source of incoming
links. The inconvenience is compounded if your traffic includes mobile-obsessed web users, as
no viable solution for accessing Google Analytics via a mobile device currently
exists.
Click here for larger image
Figure 1. Google Analytics Report Configuration
Thankfully, last year Google made the
Google Analytics Data Export API available for public use. Although still in beta,
it already provides a powerful yet simple way to access your GA data and
format it in a manner most convenient for your consumption, whether that's by
integrating it into a corporate dashboard, monitoring trends using a desktop
application, or creating a simple mobile interface. In this article, I'll show
you how to begin taking advantage of this API to create a handy interface
for web consumption.
Introducing the Google Analytics Data Export API
Like many web services, the Google Analytics Data Export API uses HTTP as the transportation protocol, responding to HTTP requests with raw XML data. Many PHP developers typically interact with web services such as this by using the
cURL extension to send the HTTP requests and a feature such as the
SimpleXML extension to parse the XML. Therefore, while you certainly can build our own solution from scratch, I suggest you use the powerful
Google
Analytics API PHP Interface (GAPI) instead. It's a powerful open source PHP class that makes interacting with the API trivial.
Browse to the
GAPI
web site to retrieve the latest version of the class, and then place it within an
appropriate place within your project directory. To use this API, You need to
enable PHP's cURL extension. (This operating system-dependent process is
well documented across the web. So, if you're not sure how to proceed, do a quick search and you'll find detailed instructions.) When you've installed it, proceed to the next section.
Connecting to the Analytics Service
Because GA data is often considered a mission-critical part of
business operations, you can't simply connect to the API and retrieve
just any web site's traffic statistics. You first need to log in to
the service so Google can confirm your account possesses the credentials
necessary to access a web site's traffic profile. Therefore, you need a
Google account, which I presume you already have configured in order to access your analytics data through the
Google Analytics web site.
You pass your account username and password to GAPI when invoking the class, like this:
require 'gapi.class.php';
$gapi = new gapi("jason@example.com", "secret")
From there, you might use the requestAccountData() method to
retrieve a list of web site profiles accessible by your account:
$gapi->requestAccountData();
foreach($ga->getResults() as $result)
{
echo "{$result} Profile ID: {$result->getProfileId()}<br />";
}
Executing this example in conjunction with my account produces the following results:
www.wjgilmore.com ProfileID: 12345678
www.easyphpweb sites.com ProfileID: 87654321
Retrieving a Web Site's Traffic Data
Notice how in the previous example I retrieved the profile IDs of each
web site associated with my account. This is relevant because you request a
web site's statistics using its assigned profile ID. You accompany the profile
ID with several parameters that determine the nature of the data you'd
like to query. You start by defining the query dimension, which
determines the context in which you'd like to view the data. For instance, you
might wish to learn more about the total number of page views for a given time
period, but in what context? Page views according to country? Browser? Visitor
type (returning or new)? You define this context (seven of which are allowed)
within the requestReportData() method's first parameter.
Next, you define the desired metrics. I already mentioned page views as a
metric example, but you can also query for useful data such as total time
spent on the site, total visitors, andif AdWords is integrated into your
Analytics accountdata such as the total number of times users clicked on a
particular ad. To view a complete list of dimensions, metrics, and other
parameters, see the
Dimensions
and Metrics Reference.
Let's consider an example. Suppose you wanted to retrieve a list of visits that have occurred during the past 24 hours according to country:
$ga->requestReportData(12345678, array('country'), // Set the context
array('visits'), // Retrieve total number of visits
array('-visits'), // Display in descending order
'', // Optional filter
'2010-03-09', // Query start date
'2010-03-09'); // Query end date
foreach($ga->getResults() as $result)
{
echo '<strong>'.$result.'</strong><br />';
echo 'Visits: ' . $result->getVisits() . '<br />';
Executing this script produces output similar to the following:
India
Visits: 11
United Kingdom
Visits: 11
United States
Visits: 9
Spain
Visits: 5
Croatia
Visits: 3
Indonesia
Visits: 3
Romania
Visits: 3
This is just one of countless query combinations at your disposal. To learn more about what's possible, see the Google Analytics Data Export API's
Data
Feed documentation.
So Much More Is Possible
The example provided in this tutorial barely touches the surface in terms of
what's possible with the Google Analytics Data Export API. Check out
this
gallery of examples for some insight and inspiration regarding just how far you
can go using this powerful API. And as always, if you've done something
interesting with what you learn in this tutorial, let us know about it in the
comments!
About the Author
Jason Gilmore is the founder of
EasyPHPWebsites.com and the author of
several popular books, including "
Easy
PHP Web sites with the Zend Framework" and "
Beginning
PHP and MySQL: From Novice to Professional" (currently in its third edition).
Check out his new DZone reference card, titled "
Getting
Started with the Zend Framework."