Google Analytics API and PHP

May 24, 2010

A few weeks ago I added stats on my Photoblog. This started out as just a link to a pie chart of cameras (tutorial here) but I started thinking I should add more than that. How about the top photos of the week and also what about top photos of all time.

There were two ways I could see gathering the stats and displaying them on my site. I could create a new table for statistics (or perhaps a column in the existing table) and then whenever someone hit that page, update the database. I would also have to include a cookie, or track their IP address so they don’t count for more than one. Or, I could leverage the power of Google Analytics, a tool that I was already using.

Class:

I am using PHP for this project.

Download the Google Analytics PHP Interface

Code:

The code below is borrowed from their documentation. I am only loading five results but it takes a few seconds to load. Because of this, I connected the code to a database, and created a cron job, so it would only run once a day. The stats that are on my site, are actually pulling from my database, which is being populated by Google Analytics.

<?php

include "googleanalytics.class.php";

try {

$ga = new GoogleAnalytics(‘username’,'password’);

$ga->setProfile(‘profile ‘); //format: ga:6089897

$ga->setDateRange(’2009-03-01′, date("Y-m-d")); //Starting date, Today’s Date

$report = $ga->getReport(

array(‘dimensions’=>urlencode(‘ga:pagePath’),

‘metrics’=>urlencode(‘ga:pageviews,ga:visits’),

‘filters’=>urlencode(‘ga:pagePath=@counter’),

‘sort’=>’-ga:pageviews’,

‘max-results’=>’5′

)

);

$x=0;

$pages = array_keys($report);

echo "<ul>";

foreach($report as $subArray){

echo "<li>" . $pages[$x] . " – " . $subArray["ga:pageviews"] . "</li>";

$x++;

}

echo "</ul>";

} catch (Exception $e) {

echo "<p>Service currently down</p>";

print ‘Error: ‘ . $e->getMessage();

}

?>

Under “filters”, I have it filtered out where the URL starts with “counter=”. This is how all my photos are named, and by adding this filter, the non-photo pages won’t show up.

Leave a Reply