PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

Google Analytics Accounts API

Note: This article was originally published at Planet PHP on 23 November 2010.
Planet PHP
I'm working with Google Analytics at the moment, to pull information about web traffic from analytics into another system. Google have excellent APIs and that makes this job much easier. I'm using pecl_oauth to authenticate users against their google accounts (see my post about using OAuth from PHP), but even after I have a valid google user, working out which analytics accounts they have access to and how to refer to them is a puzzle in itself, so I thought I'd share what I learned.These examples use pecl_http, since I have control of my platform and I find it easy to work with. I've tried to write this with explanations of the overall process in between the code snippets so hopefully this makes the process clear whether or not you will use exactly the same implementation.

Analytics Accounts


Your google account can have access to one or more analytics accounts. For example when I log in I have access to accounts which hold the data for lornajane.net, phpwomen.org, joind.in and a few other things I'm involved with. Only lornajane.net actually belongs to me, the others are accounts created by someone else and which I have access to. The first challenge therefore is to work out which a user has access to - the best place to start is the reference page for the Management API, part of google's own documentation. In a nutshell, we build up a URL like this, being increasingly specific by fleshing out the values in square brackets on subsequent calls:

https://www.google.com/analytics/feeds/datasources/ga/accounts/[accountID]/
webproperties/[webPropertyID]/profiles/[profileID]/goals


First up then, is to get a list of accounts for our authorized user - I already have a valid oauth access token to use in this example
A A A A A A $oauth = new OAuth($consumer_key,
A A A A A A A A A A A A $consumer_secret
A A A A A A A A A A A A);
A A A A A A $oauth-setToken($access_token, $access_token_secret);

A A A A A A $result = $oauth-fetch('https://www.google.com/analytics/feeds/datasources/ga/accounts');
A
This returns some XML containing some information about the results and an element for each account. The key information you want here is inside the entries, there are tags, and here we can find both the account name and it's identifier. To retrieve these in a nice list, I used code that looked like this:

A A A A A A if($result) {
A A A A A A A A $response = $oauth-getLastResponse();
A A A A A A A A $xml = new SimpleXMLElement($response);
A A A A A A A A $xml-registerXpathNamespace("w3", "http://www.w3.org/2005/Atom");
A

Truncated by Planet PHP, read more at the original (another 18932 bytes)