How to Create Graphs with Google Analytics API

Learn how to create a Google Analytics graphs with all the visits received in your website, using the Google Analytics API. First, you need to copy all the files contained in this .zip file to any hosting or local environment with PHP 5.x. Insert your user and password inside grafico.php , and then run it in your browser. You'll see a graph with all the visits received in your website in the last 15 days, excluding Italy.

I'll explain, step by step, the code used so you can also create your own graphs with Google Analytics API and change the parameters as you wish. At the end of this post, you'll see the complete code. We'll start with this line:

include "function_dates.php"; include "googleanalytics.class.php";

This part includes two essential files: 1) function_dates.php createDateRangeArray() will be used to create an array with all the existing days between two dates (see http://boonedocks.net/mike/archives/137-Creating-a-Date-Range-Array-with-PHP.html); 2) googleanalytics.class.php includes the instructions to get connected to the Google Analytics API (see http://www.askaboutphp.com/63/google-analytics-api-class-for-php.html).

$fecha2 = date('Y-m-d');
$fecha1 = strtotime ('-15 day' , 
strtotime ($fecha2)) ;
$fecha1 = date ('Y-m-d', $fecha1);
$fechas = createDateRangeArray($fecha1,$fecha2);
$days = count($fechas);

This part detects the last 15 days (you can stretch it). The important thing is defining $fecha1 (first day) y $fecha2 (last day).

try {
$ga = new GoogleAnalytics('usuario@gmail.com','password');
$ga->setProfile('ga:48231979');
$ga->setDateRange($fecha1,$fecha2);

This part performs the Google authentication process in Google Analytics. You should add: 1) your Google Analytics user, 2) your password, 3) the profile to which you'd like to perform the query. You should add ga: before the profile number (example: ga:48231979). Note: profile number isn't the same as account number (UA-...). An account can contain many profiles, so you should find the profile you actually need inside the Administrator of Google Analytics.

Also, it's recommendable that you use a user only authorized to see reports, which you can accomplish through the User Administrator inside the desired profile of Google Analytics.

$report = $ga->getReport(
array('dimensions'=>urlencode('ga:date'),
'metrics'=>urlencode('ga:visits'),
'filters'=>urlencode('ga:country!=@Italy'),
'sort'=>'ga:date'
)
);

In this part we'll get a visits per day report excluding Italy, sort by days. $report is a multidimensional array with dimensions and their metrics. var_dump($report) allows to see the whole report. Read the data exportation API of Google Analytics to discover more combinations of dimensions, metrics and filters.

$i = 0; $serie_dim = null; $serie_val = null;

foreach ($report as $valor){

$serie_dim .= "'".$fechas[$i]."', ";
$serie_val .= $valor['ga:visits'].", ";
$i++;

}

$serie_dim = substr($serie_dim, 0, -2); $serie_val = substr($serie_val, 0, -2);

In this, we transform data to the format required by Highcharts to create the graph.

$script1 = "<script type='text/javascript'
src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
'></script><script type='text/javascript'>// <![CDATA[
var chart;$(document).ready(function() {chart=new Highcharts.Chart({chart:{
renderTo:'container',defaultSeriesType:'line',marginRight:130,marginBottom:25},
title:{text:'VISITAS POR DÍA (Últimos 15 días, excepto desde Italia)',x:-20},
subtitle:{text:'Fuente: Google Analytics',x:-20},xAxis:{categories:['.
$serie_dim.']},yAxis:{title:{text:'Visitas'},plotLines:[{value:0,width:1,
color:'#808080'}]},tooltip:{formatter:function(){return'<b>'+this.series.name
+'</b>'+this.x+': '+this.y+'';}},legend:{layout:'vertical',align:'right',
verticalAlign:'top',x:-10,y:100,borderWidth:0},series:[{name:'Visitas',
data:['.$serie_val.']}]});});// ]]></script><script type='text/javascript
' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
'></script><script type='text/javascript' src='highcharts.js'></script>
<script type='text/javascript' src='exporting.js'></script><div id='
container' style='width: 800px; height: 400px; margin: 0 auto;'></div>";

This is the minified Javascript code used by Highcharts to create a line graph. Use Minifier to compress any code.

echo $script1;

Here we'll execute the Javascript code to retrieve the source code of Highcharts. This is the complete code for creating the whole graph:

<!--?php include "function_dates.php"; include "googleanalytics.class.php"; 
$fecha2 = date('Y-m-d'); $fecha1 = strtotime ('-15 day', 
strtotime ($fecha2 ) ); $fecha1 = date ('Y-m-d' , $fecha1 ); 
$fechas = createDateRangeArray($fecha1,$fecha2); 
$days = count($fechas); 
try { $ga = new GoogleAnalytics('usuario@gmail.com','password'); 
$ga->setProfile('ga:48231979');
$ga->setDateRange($fecha1,$fecha2);

$report = $ga->getReport(

array('dimensions'=>urlencode('ga:date'),
'metrics'=>urlencode('ga:visits'),
'filters'=>urlencode('ga:country!=@Italy'),
'sort'=>'ga:date'
)
);

$i = 0; $serie_dim = null; 
$serie_val = null;

foreach ($report as $valor){

$serie_dim .= "'".$fechas[$i]."', ";
$serie_val .= $valor['ga:visits'].", ";
$i++;

}

$serie_dim = substr($serie_dim, 0, -2); $serie_val = substr($serie_val, 0, -2);

$script1 = "<script type='text/javascript'
src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
'></script><script type='text/javascript'>// <![CDATA[
var chart;$(document).ready(function() {chart=new Highcharts.Chart({chart:{
renderTo:'container',defaultSeriesType:'line',marginRight:130,marginBottom:25},
title:{text:'VISITAS POR DÍA (Últimos 15 días, excepto desde Italia)',x:-20},
subtitle:{text:'Fuente: Google Analytics',x:-20},xAxis:{categories:['.
$serie_dim.']},yAxis:{title:{text:'Visitas'},plotLines:[{value:0,width:1,
color:'#808080'}]},tooltip:{formatter:function(){return'<b>'+this.series.name
+'</b>'+this.x+': '+this.y+'';}},legend:{layout:'vertical',align:'right',
verticalAlign:'top',x:-10,y:100,borderWidth:0},series:[{name:'Visitas',
data:['.$serie_val.']}]});});// ]]></script><script type='text/javascript
' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
'></script><script type='text/javascript' src='highcharts.js'></script>
<script type='text/javascript' src='exporting.js'></script><div id='
container' style='width: 800px; height: 400px; margin: 0 auto;'></div>";

}catch (Exception $e) {

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

}

echo $script1;

?>

Download the .zip file with this code and all the needed files from here. If you know a little of PHP, you can create custom graphs just changing dimensions and metrics after (reading about the exportation data API from Google Analytics). To create graphs, there are also other alternatives such as Google Charts or amChart.

Update 18-04-2012: Instead of using the function createDateRangeArray, you can also take dates directly from Google Analytics. However, I prefer the first option since it allows getting a clean dates array instead of the confusing format provided by Google Analytics (ex. 20120318). Besides, you'll be able to use this same array to perform queries to other databases, where not all dates have an associated value.

Contribute with a comment comment0 Comments
mode_editContribute with a comment

menu
menu