Monday, May 24, 2010

10:33 PM
Google Analytics is an outstanding website analytics tool that gives you way more information about your website than you probably need. Better to get more than you want than not enough, right? 


Anyways I check my website statistics more often than I should and it ends up taking a few minutes to get logged in, select the right site, select the current day, etc. I found a great Google Analytics PHP API that allows me to get just the statistics I’m looking for.


The PHP Library

The PHP class I found, analytics, can be downloaded at http://www.swis.nl/ga/. The site also gives a few solid examples.

The PHP


//session_start for caching, if desired
session_start();
//get the class
require 'ga/analytics.class.php';
//sign in and grab profile
$analytics = new analytics('david@davidwalsh.name', 'myP@ssw0rd');
$analytics->setProfileByName('davidwalsh.name');
//set the date range for which I want stats for (could also be $analytics->setDateRange('YYYY-MM-DD', 'YYYY-MM-DD'))
$analytics->setMonth(date('n'), date('Y'));
//get array of visitors by day
print_r($analytics->getVisitors());
//get array of pageviews by day
print_r($analytics->getPageviews());

As you’d expect, we first grab the class and immediately sign providing your credentials and website profile (you can just use your domain). Once authenticated we set a date range and retrieve our visitors and pageviews.

The Sample PHP Results

The above code retrieved visits and pageviews for the current month. What’s returned is an array that looks as follows:
Array
(
    [01] => 6539
    [02] => 6677
    [03] => 6160
    [04] => 5563
    [05] => 2964
    [06] => 2973
    [07] => 5080
    [08] => 6078
    [09] => 5927
    [10] => 6177
...
)
A very simple array numbered by day. You could do anything you wanted with the array — create averages, peaks, lows, etc.

Advanced Usage

The analytics class also allows you to retrieve search keywords and anything else you might like:
$keywords = $analytics->getData(array(
'dimensions' => 'ga:keyword',
               'metrics' => 'ga:visits',
               'sort' => 'ga:keyword'
)
);
The PHP analytics class is a masterpiece. Rest assured I’ll be doing a ton of work with this class for customers and my own websites

0 comments: