Posted By

dtbaker on 12/18/10


Tagged

google graph Analytics


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

notturnale
iyezine


Google Analytics PHP Example


 / Published in: PHP
 

URL: http://dtbaker.com.au/random-bits/google-analytics-php-api.html

Example of using http://code.google.com/p/gapi-google-analytics-php-interface/ to graph google analytics data.

  1. <?php
  2.  
  3. // include the GAPI class from http://code.google.com/p/gapi-google-analytics-php-interface/
  4. require_once 'gapi.class.php';
  5.  
  6. // login details for the account that has access to analytics reports.
  7. define('ga_web_email', '[email protected]');
  8. define('ga_web_pass', 'password');
  9.  
  10. // use our caching function above to get some results in a nice array
  11. // change 123456789 to your google analytics id.
  12. $data = get_analytics_data('123456789',array('date'),array('newVisits','visits'));
  13. // output the image:
  14. output_image($data);
  15.  
  16.  
  17. function get_analytics_data(
  18. $profile_id,
  19. $dimensions=array('browser'),
  20. $metrics=array('pageviews','visits','UniquePageviews'),
  21. $sort=null,
  22. $start_date=null,
  23. $end_date=null
  24. ){
  25. $cache_id = md5(serialize(func_get_args()));
  26. $return = false;
  27. // check if the cache item exists.
  28. $temp_folder = '/tmp/ga/';
  29. if(!is_dir($temp_folder))mkdir($temp_folder);
  30. $filename = $temp_folder.$cache_id;
  31. if(is_file($filename)){ // if cache entry exists
  32. if(filemtime($filename) > (time() - 172800)){ // check if it's older than 2 days
  33. $return = unserialize(file_get_contents($filename)); // grab the cached content.
  34. }
  35. }
  36. if(!$return){
  37. // no cache item found, so we grab it via gapi class.
  38. $ga = new gapi(ga_web_email,ga_web_pass);
  39. if(!$sort)$sort = current($dimensions);
  40. ini_set('display_errors',true);
  41. $ga->requestReportData($profile_id,$dimensions,$metrics,$sort,null,$start_date,$end_date,null,100);
  42. $return = array();
  43. $return['data'] = array();
  44. foreach($ga->getResults() as $result){
  45. $data = array();
  46. foreach($dimensions as $d){
  47. $data[$d] = (string)$result;
  48. foreach($metrics as $m){
  49. $data[$m] = $result->{'get'.$m}();
  50. }
  51. }
  52. $return['data'][] = $data;
  53. }
  54. $return['total'] = $ga->getTotalResults();
  55. foreach($metrics as $m){
  56. $return[$m] = $ga->{'get'.$m}();
  57. }
  58. $return['timestamp'] = $ga->getUpdated();
  59. }
  60. // save cache item.
  61. file_put_contents($filename,serialize($return));
  62. return $return;
  63. }
  64.  
  65.  
  66. function output_image($data){
  67. $max_y = 500;
  68. $width = 640;
  69. $height = 200;
  70. $attr=array();
  71. $days = count($data['data'])-1;
  72. // work out the width of 1 day
  73. $day_width_percent = round((100 / $days)/100,4); // 15% will be 0.15 1% will be 0.01
  74. $half_day_width = round($day_width_percent/2,4);
  75. $attr['chxl'] = '1:'; // the data point label text.
  76. $attr['chxp'] = '1'; // the data point label positions.
  77. $attr['chxr'] = '0,0,'.$max_y.'|1,0,'.$days; // the min/max data range to graph over the space of the image.
  78. $attr['chxt'] = 'y,x'; // ?
  79. $attr['chs'] = $width.'x'.$height; // width x height of the image.
  80. $attr['cht'] = 'lc'; // type of graph
  81. $attr['chco'] = '3D7930,FF9900'; // colors of the graph lines.
  82. $attr['chds'] = '0,'.$max_y.',0,'.$max_y.''; // data range of each data set (0 to 500 each)
  83. $attr['chdl'] = 'Visits|New Visits'; // labels for each data set
  84. $attr['chg'] = (100/$days) . ',' . ((100/$max_y)*100) . ',4,1,-'.($half_day_width*100).',0'; // (vert,horiz) how many step lines.
  85. $attr['chls'] = '2,4,0|1'; // ?something about size of lines maybe?
  86. $attr['chtt'] = 'Visits vs New Visits over past '.$data['total'].' days.'; // graph label at the top.
  87. // graph stripes. every saturday and sunday ?
  88. // work out what day the graph starts on.
  89. $first = current($data['data']);
  90. $start_day = date('N',strtotime($first['date']));
  91. // how big is the first bar?
  92. // highlight white from first bar to first Saturday (6)
  93. $attr['chf'] = 'c,ls,0';
  94. $number_of_days = 6 - $start_day;
  95. if($number_of_days>0){
  96. // we start with a white bar, because we're starting graph during the week.
  97. $color='FFFFFF';
  98. $attr['chf'] .= ','.$color.','.(round($number_of_days*$day_width_percent,5)-$half_day_width);
  99. }else{
  100. // we're starting graph on a saturday or sunday.
  101. $color='EFEFEF';
  102. $attr['chf'] .= ','.$color.','.(round((8-6)*$day_width_percent,5)-$half_day_width);
  103. // then we do 5 days white.
  104. $attr['chf'] .= ',FFFFFF,'.round(5*$day_width_percent,5);
  105. }
  106. // loop over for the remaining days, every 7 days different colour.
  107. for($x=0;$x<=$days;$x+=7){
  108. // we're doing 2 days dark for weekend.
  109. $attr['chf'] .= ',EFEFEF,'.round(2*$day_width_percent,5);
  110. // we're doing 5 days white.
  111. $attr['chf'] .= ',FFFFFF,'.round(5*$day_width_percent,5);
  112. }
  113.  
  114. $p = $start_day;
  115.  
  116. $x=0;
  117. $points1 = $points2 = '';
  118. foreach($data['data'] as $d){
  119. if($p%7==1){
  120. // every monday put a date.
  121. $attr['chxl'] .= '|Mon' . date('jM',strtotime($d['date']));
  122. $attr['chxp'] .= ',' . $x;
  123. }
  124. $points1 .= $d['visits'].',';
  125. $points2 .= $d['newVisits'].',';
  126. $x++;
  127. $p++;
  128. }
  129.  
  130. $attr['chd'] = 't:' . rtrim($points1,',') . '|' . rtrim($points2,',');
  131. ?>
  132. <img src="http://chart.apis.google.com/chart?<?php foreach($attr as $k=>$v) echo $k .'='.urlencode($v).'&
  133. ';?>" width="<?php echo $width;?>"
  134. height="<?php echo $height;?>" alt="<?php echo $attr['chtt'];?>" />
  135. <?php
  136. }
  137. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: jorg on January 18, 2011

Using this code I got a white page any ideas to fix it?

Posted By: Monkeybrain on January 19, 2011

Got same result, blank page. Checked credentials and everything's right.

Posted By: dtbaker on January 31, 2011

Snippet updated, it was missing the output_image() call.

You need to login to post a comment.