Highlight your site’s hot content with the Google Analytics API

Google Analytics logo Want to highlight the most popular articles, blog posts or media on your website? If you use the excellent Google Analytics to track the usage of your sites, you can use the Google Analytics API to create an automatically updated hot-list of popular content.

In this tutorial I’ll explain how I managed to create the “hot trends” list on What The Trend?. This shows the most popular “trends” on the site from the last 3 days.

What's hot

You might ask, why do I need to use Google Analytics for this, why not for example log to my database every time an article is viewed or video is watched. Here are a few advantages of this method:

  • More accurate results: cached pages are still counted, search engine spiders are ignored
  • Reduces the number of database queries needed
  • Easy to filter the results, for example find the most popular content for visitors from a certain country
  • Easy to use different metrics, for example most page views or most unique visitors

I’ll be using PHP, but similar steps should work for any language if you have the ability to make HTTP requests and parse XML.

Introducting the Google Analytics Data Export API

Although its a bit of a mouthful, the Google Analytics Data Export API allows you to connect to Google Analytics, and extract almost any data about your site’s current and historical traffic.

The basic steps are:

  1. Authenticate – there are three methods of authentication: AuthSub proxy authentication, OAuth authentication for web applications and ClientLogin username/password authentication
  2. Get the list of accounts via a call to https://www.google.com/analytics/feeds/accounts/default
  3. Retrieve the data via a call to https://www.google.com/analytics/feeds/data

To abstract away some of the complexities of authenticating and constructing the URLs needed to retrieve data, it’s best to use a client library. Google provides client libraries for Java and Javascript and there are several other third party libraries.

I chose to use the PHP library provided by RawSEO.com

require_once 'googleAPI.class.php';
//replaced with real Google Analytics authentication data
$gapi = new googleAPI('someone@example.com','mypassword',"www.whatthetrend.com");

Using the library is simple. The constructor for the googleAPI object takes three strings: your email, password and profile name.

$now=date('Y-m-d'); // returns todays date in the form 2009-06-19
$then=date('Y-m-d',time()-72*60*60); // three days ago
$reportData =  $gapi->viewReport($then,$now,"ga:pageviews","ga:pagePath");

The viewReport method takes four strings: two date strings for the start and end of the reporting period, then a list of metrics and dimensions. Metrics are “aggregated statistics for user activity”, things like page views, number of visitors and bounce rates. Dimensions are ways to slice and dice data about visitors and content: for example content by page title or url, or visitors by browser or city.

We have a very simple query: just return us the number of page views “ga:pageviews” for each distinct URL “ga:pagePath”. This will return us an array of paths and pageviews.

Let’s loop through the result set and extract the information we’re interested in. Typically, you may want to ignore certain pages like the homepage or help pages. All trend pages on What the Trend start with the string “/trend/”, so we’ll take those items and discard the rest.

$trends=array(); // make a temp array for storing results
foreach ($reportData as $r) {
	if (strpos($path,'/trend/')===0) { //check the path starts with /trend/
		$trendName=urldecode(substr($path,strlen('/trend/'))); //chop off the 'trend' part of the url
arsort($trends); // sort by the number of pageviews, descending
$slice=(array_slice($trends,0,8)); //we just want the top 8 trends

Now we have our most popular trends formatted in a nice array, like this:

Array (
[iPhone] => 120,
[France] => 54,
[ReignDesign] => 27,
[Cool stuff] => 3

It’s now simple to take this array and look up any extra info (for example, you could extract the title of the page from your database).

I set up a cronjob to write out the current trends to a static html file once per hour. This is then included in other pages on the site.

I hope you find this quick tutorial useful and can adapt it for use on your site!

Matt Mayer

Matt Mayer is a founder at ReignDesign. Matt is from the UK and was based in Shanghai for ten years. He is now living in Bangkok, Thailand.


Leave a Reply

Your email address will not be published. Required fields are marked *

Share this post