GA marblesAbout a month back, Google opened the Google Analytics API service to all Analytics users. the API allows developers to integrate the GA reports into their own applications or websites, or even access the reports from a phone!

I’ve been thinking about how I can make use of this API to enhance the sites I’m working on. But before kicking off ideas, I had to find out how to access and use the API. I finally came up with a PHP class that will do all the grunt work of calling the API, you just need to supply your report’s parameter and the PHP class will return you an array of Analytics data.


Getting Started
Ok, first thing’s first, you need to have Google Analytics (obviously) and login credentials to GA. Then you should download my PHP class available at the end of this post.

To access the API is basically a 2 step process. First is to authenticate against Google with your GA account credentials to get an authentication code. After that you can use the authentication code to access your list of website profiles in GA and extract out the data you want.

Google Analytics PHP Class
Here’s how you access a report showing pageviews and visits, by date and country, filtered by ‘Australia’, sorted by pageviews in descending order.

setProfile('{GA Profile ID}');

	// set the date range we want for the report - format is YYYY-MM-DD
	$ga->setDateRange('2009-04-01','2009-04-07');

	// get the report for date and country filtered by Australia, showing pageviews and visits
	$report = $ga->getReport(
		array('dimensions'=>urlencode('ga:date,ga:country'),
			'metrics'=>urlencode('ga:pageviews,ga:visits'),
			'filters'=>urlencode('ga:country=@Australia'),
			'sort'=>'-ga:pageviews'
			)
		);

	//print out the $report array
	print_r($report);
	
} catch (Exception $e) { 
	print 'Error: ' . $e->getMessage(); 
}
?>

Hopefully, the code is quite self-explanatory. setProfile() requires your website profile id number. To get the profile id number, you go to your GA dashboard, click on ‘View Report’ for your website, and look at the URL. There should be an ‘id=xxxxxx’ in the URL. That is your id number. You have to specify it as ‘ga:xxxxxxx’ in setProfile().

Profile ID Alternatively, included within the class is a function called getWebsiteProfiles(), if you call this function, after authenticating, you will get an array of all the website profiles available under your account. You can find the id number from there also.

The only major function you need to really pay attention to is the getReport() function. This is where you craft the report parameters that you want results from.

If you’re familiar with GA, you will know that GA basically works with 2 field types – dimensions and metrics. If you’re not sure of what these these things are, I recommend reading the Google documentation on them. Simplistically, you could think of metrics as the columns of your GA reports, and dimensions as the rows.

Google has also listed out the available dimensions and metrics you can use in the API.

With the getReport() function, you are basically doing the same thing as the Custom Reports feature of GA. You decide which dimension and metrics you want and the API will return you the data.

What you will get from getReport() is an array that looks something like this:

Array
(
    [20090401~~Australia] => Array
        (
            [ga:pageviews] => 6
            [ga:visits] => 3
        )

    [20090402~~Australia] => Array
        (
            [ga:pageviews] => 4
            [ga:visits] => 3
        )

    [20090407~~Australia] => Array
        (
            [ga:pageviews] => 4
            [ga:visits] => 4
        )

    [20090403~~Australia] => Array
        (
            [ga:pageviews] => 3
            [ga:visits] => 3
        )

    [20090405~~Australia] => Array
        (
            [ga:pageviews] => 3
            [ga:visits] => 3
        )

    [20090406~~Australia] => Array
        (
            [ga:pageviews] => 3
            [ga:visits] => 3
        )

    [20090404~~Australia] => Array
        (
            [ga:pageviews] => 2
            [ga:visits] => 2
        )
)

To keep the array simple, I’ve basically pushed the dimensions as the 1st array dimension keys, separated by ‘~~’ pattern so that you can parse the keys if you require. The metrics are listed in the sub-array, with the metric as the key and value of the metric.

Do know that not every dimension has a corresponding metric. Google has put up a compatibility chart for you to verify which combination of dimensions and metrics are valid.

This class requires the use of the cURL function in PHP. The functions are normally enabled, but if its not, here a guide on how you enable cURL in PHP.

That’s basically it. Feel free to download the class and play with it. Do bear in mind that this is not a ‘production’ ready class. There’s hardly any validation and error checking and die() is not the best fail-safe method for the class to fail gracefully. When I have more time, I will look at improving the class.. The class has been updated with some exception catching, so hopefully this will give more meaningful error messages for those of you facing problems.

Download: download icon

Here are some more examples of reports you can create:

// what browsers visitors to your using?
$report = $ga->getReport(
	array('dimensions'=>urlencode('ga:browser'),
		'metrics'=>urlencode('ga:visits'),
		'sort'=>'-ga:visits'
		)
	);

// which are your top landing pages and how long they spent on the page?
$report = $ga->getReport(
	array('dimensions'=>urlencode('ga:landingPagePath,ga:pageTitle'),
		'metrics'=>urlencode('ga:entrances,ga:timeOnPage'),
		'sort'=>'-ga:entrances'
		)
	);

// which are your top internal search keywords by pageviews?
$report = $ga->getReport(
	array('dimensions'=>urlencode('ga:searchKeyword'),
		'metrics'=>urlencode('ga:pageview'),
		'sort'=>'-ga:pageviews'
		)
	);

UPDATE 2009-07-15: Google has posted new updates to the Google Analytics API. The changes includes new limit on the amount of data returned, and relaxed restrictions on combinations of dimensions and metrics.