Recently Google put 2 APIs in commission. While Google Analytics API, the first one of them enables developers to integrate GA profile information details, reports and the statistical data with their web and mobile applications by accessing read-only to their existing Google Analytics profiles through their client applications they developed, Google Chart API provides you to create dynamic graphical charts in PNG format and in various kinds (Bar, Line, Radar, Scatter plot, Venn diagram, Pie, Google-o-meter, Maps) by means of URLs that you’ll specially form as frequent inputs.
For both my curiosity about graphical analysis and as because I think it will offer rich and totally dynamic content inside the applications when these two powerful tools are combined together, I decided to research more in depth about both two APIs. Naturally, for the purposes of conforming my own web applications, PHP classes targeting these APIs were at the basis of my research among existing Java/HTTP source codes and libraries which are being supported by Google Analytics Team and also Phyton, PHP, Ruby based libraries which are being contributed (or being supported) by users. When I realized that couple of people wrote greatly handy classes respectively for both but there was no sufficient work as I hope about the integration of them together, I decided to implement the integration by myself. Consequently, I was able to achieve an integration which can generate realtime dynamic graphical analysis outputs as you can see below and at my home page.
Among the various sample classes I tried, I would like to thank Eldee for his Google Analytics API PHP and Andrey Savchenko (Rarst) for his Google Chart API which I used inside my application being appreciative of their coding accuracy and the proper array ouputs.
Thanks to dynamic realization of the details such as scaling of x and y axes, labeling, tick positioning and the data feed itself, this study enables GA graphical analysis to be developed and conducted within our various applications without the need of any manipulation by hand. Furthermore, what sort of advantages does it provide us ?
- We do not have to logon to GA web interface constantly in order to follow up analysis regarding our web applications.
- We automize the data flow needed to constitute the charts and gain constant realtime data feed.
- We don’t need to store, backup and maintain the data on our local systems.
- We assign bandwidth usage and relevant service load to Google servers.
- We don’t have to depend on any software format as we have the charts made in accordance with the functional and visual criteria we choose.
- We provide rich statistical presentations inside our blog applications like Wordpress, without the need of the plugins which store and query the data on our local resources.
- We’re being able to have multiple web app. or blog analysis within one centeral management point and publish realtime geographic/demographic statistics on charts by the help of ga: query parameters such as sort and filters.
You may edit the code below in accordance with your needs and use it to generate dynamic charts in different shapes and forms but don’t forget to download the classes from the websites I’ve given the links above, as you’ve to include them in order to make this code run. If you use and appreciate my code, referencing or providing a trackback to my site will please me.
<?php
// PHP Integration of "Google Analytics API" with "Google Chart API" for creating realtime dynamic statistics chart.
//
// Sezgin Bayrak, ipsure.com (2010)
require 'google_chart.php'; // By Andrey Savchenko (Rarst), http://www.rarst.net/script/google-chart/
include "googleanalytics.class.php"; // By Eldee, http://www.askaboutphp.com/63/google-analytics-api-class-for-php.html
// Set first date you want your GA stats begin to be collected
$lastMonth = date("Y-m-d", $_SERVER['REQUEST_TIME'] - 2592000);
$today = date("Y-m-d");
try {
// Create an instance of the GoogleAnalytics class using your own Google {email} and {password}
$ga = new GoogleAnalytics('your_account@gmail.com','your_password');
// Set the Google Analytics profile you want to access - format is 'ga:123456';
$ga->setProfile('ga:xxxxxxxx');
// Setting date range with pre-defined variables
$ga->setDateRange($lastMonth,$today);
// Generating report arrays for the date range, consisting of pageviews and visits
$report = $ga->getReport(
array('dimensions'=>urlencode('ga:date'),
'metrics'=>urlencode('ga:pageviews,ga:visits,ga:newVisits'),
)
);
// Arrange "page views" as a new array
$pviews = array();
foreach($report as $dimension => $metrics) {
array_push($pviews, $metrics['ga:pageviews']);
}
// Arrange "visists" as a new array
$visits = array();
foreach($report as $dimension => $metrics) {
array_push($visits, $metrics['ga:visits']);
}
// Extract various dates from the report array keys in order to use them as variables for x-axis labels
$days = array_keys($report);
list($d0, $d1, $d2, $d3, $d4, $d5, $d6, $d7, $d8, $d9, $d10, $d11, $d12, $d13,
$d14, $d15, $d16, $d17, $d18, $d19, $d20, $d21) = $days;
} catch (Exception $e) {
print 'Error: ' . $e->getMessage();
}
// Get the keys for max. values of page views and visits
function max_key($array) {
foreach ($array as $key => $val) {
if ($val == max($array)) return $key;
}
}
$array = $pviews;
$precord = max_key($array);
$array = $visits;
$vrecord = max_key($array);
// Always use max. value recorded in array for y-axis
$ymax = 1*(max($pviews));
// Devide it by six and round up to nearest whole number to set appropriate y-axis ticks
$ytick = ceil((max($pviews))/6);
// Chart settings
$traffic = new GoogleChart;
$traffic->type='lc';
$traffic->SetImageSize(600,200);
$traffic->SetChartMargins(0,30,0,0);
$traffic->SetEncode('simple');
$traffic->AddData($visits);
$traffic->AddData($pviews);
$traffic->AddChartColor('FF9900');
$traffic->AddChartColor('0077CC');
$traffic->AddLineStyle(3);
$traffic->AddLineStyle(2,5,5);
$traffic->AddDataLineStyle('0077CC',1,'0:30',3);
$traffic->AddFillArea('B','FF99007F',0);
$traffic->AddFillArea('b','E6F2FA7F',0,1);
$traffic->AddShapeMarker('o','666666',0,30,8);
$traffic->AddShapeMarker('o','FF9900',0,30,6);
$traffic->AddShapeMarker('o','555555',1,30,8);
$traffic->AddShapeMarker('o','0077CC',1,30,6);
$traffic->AddShapeMarker('o','666666',0,$vrecord,6);
$traffic->AddShapeMarker('o','900C0C',0,$vrecord,4);
$traffic->AddShapeMarker('o','666666',1,$precord,6);
$traffic->AddShapeMarker('o','900C0C',1,$precord,4);
$traffic->AddAxis('y,x');
$traffic->AddAxisRange(0,$ymax,$ytick);
$traffic->AddAxisLabel(array($d0,$d7,$d14,$d21,'Now'),1);
$traffic->SetGrid(round(100/4,2),0,1,3);
$traffic->AddAxisStyle('0000DD',1,0);
$traffic->AddAxisTickLength(-600,0);
$traffic->SetTitle('Visits/Page Views of Last 30 Days');
$traffic->AddLegend('visits');
$traffic->AddLegend('page views');
$traffic->SetLegendPosition('b');
$traffic->AddDataPointLabel('f',($visits[30]),'000000',0,30,12);
$traffic->AddDataPointLabel('f',($pviews[30]),'000000',1,30,12);
$traffic->AddDataPointLabel('t',(max($visits)).' max','900C0C',0,$vrecord,12);
$traffic->AddDataPointLabel('t',(max($pviews)).' max','900C0C',1,$precord,12);
// Generate chart URL
echo $traffic->GetImg();
?>
Following my first sample, I plan to continue my researches and efforts over combining two APIs in multiple ways using PHP. When I work on new codes about the relevant subject, I’ll gladly share it here with you. If you also have different attempts and ideas over the subject, we can go further into this matter here.
Related Posts
No related posts.







RSS feed for comments on this post.




