Google Analytics API: stacked pageviews

Recently, Rand Fiskin from SEOmoz wrote a great article on how to create a custom Google Analytics report with Excel/Openoffice Calc. If you did not read it yet, please do it now.

I think that it's an excellent idea, however I was quite turned down by the amount of work for the manual data gathering. I knew that Google Analytics has an API for such things, but I never had a reason to use it until today. So I just wrote a few lines of PHP to query the API and spit out the raw data in CSV format.

The ZIP file above contains two files: GoogleAnalyticsAPI.class.php and runme.php which contains the following config section:

 *  Step 4: Config your metrics
 *          This is where it gets interesting

$enddate = strtotime('last Saturday');  // alternatively use strtotime('2015-04-12') for example
$startdate = strtotime('-6 days -13 weeks', $enddate);
$metric = 'ga:pageviews'; // alternatively use 'ga:visits'

$filters = array();
$filters['Firefox'] = 'ga:browser=@Firefox';
$filters['Safari'] = 'ga:browser=@Safari';

The interesting part is the $filters array: Here you can put all your segmentations. In the example above, we get Firefox users vs. Safari users. If you want to get something similar to Rand Fiskin's post, use this:

$filters['Blog'] = 'ga:pagePath=@/blog';
$filters['YOUmoz'] = 'ga:pagePath=@/ugc';

There are a lot of other filters available. If you are interested, you can read about other available dimensions (especially the "Session" and "Page Tracking" parts) at Google's API Documentation.

Before you run the script for the first time, you also need to complete the configuration steps one to three as documented in the source code. This is necessary to authenticate to the Google API.