PHP Classes
PHP Classes
elePHPant
Icontem

Tracking PHP API Accesses using Google Analytics Part 1: Retrieving Access Statistics - PHP Google Analytics API Metrics Tracker package blog

Recommend this page to a friend!
  All package blogs All package blogs   PHP Google Analytics API Metrics Tracker PHP Google Analytics API Metrics Tracker   Blog PHP Google Analytics API Metrics Tracker package blog   RSS 1.0 feed RSS 2.0 feed   Blog Tracking PHP API Acce...  
  Post a comment Post a comment   See comments See comments (4)   Trackbacks (0)  

Author:

Updated on: 2015-10-20

Posted on:

Package: PHP Google Analytics API Metrics Tracker

Google Analytics is a popular tool used by many sites to keep track of the statistics of the visitors of the sites.

However, it also provides an API that lets you do more than that, like for instance keeping track of the accesses to the APIs of your own sites, as well building custom user user interfaces to view the access statistics in the way that is most convenient for the site managers.

Read this part of the article to learn how to use the Google Analytics API to retrieve and display your site statistics that you need to generate custom reports.


 



Contents

Introduction

Retrieving Google Analytics Data to Build a KPI Dashboard

Conclusion


Introduction

As we all know, many web projects are created in order to solve particular business needs. Any business requires data on how well it is going, how big the traffic of clients is, how many clients register, etc..

Google Analytics is an industry standard service to collect such data. The site webmaster puts a JavaScript tracker script in the pages to allow Google Analytics to collect the data for every time a page is loaded.

Google Analytics Charts

All that is done on front-end site, no PHP code is involved. In this article I cover retrieving access statistics data from Google Analytics using PHP.

Retrieving Google Analytics Data to Build a KPI Dashboard 

Project owners and investors might need a dashboard or KPI progress page. Let's see how to grab statistics from your Google Analytics account to s PHP backend in order to build a dashboard.

There are many statistics that represent the heartbeat of your project: number of visitors, bounce rate, percent of registrations, profit from every user, etc. These are called KPIs: the key performance indicators, each of which is a business metric used to evaluate factors that are crucial to the success of an organization.

KPIs differ from one company to another.  Some of these indicators can be seen in original Google Analytics reports: how many people came and how engaged they are in average. What your customer might want is to combine that data with revenue and profit data from your database and build a solid dashboard.

At this point you will realize that you need to retrieve Google Analytics data from your PHP scripts.
Hold on, Google Analytics is a complex data source, —entries can be queried by date and name.

You will find an couple of classes below that help to automate interaction with this service and return a simple number as result of your query. The code is based on Zend Framework 1, since it helps a lot to automate interaction with Google services (a technology called GData).

First, let's create an abstract class to help us create classes to work with different Google Services (just replace XXX with your app or library name)

<?php

class XXX_Google_Wrapper_Abstract {

    public $gdClient; 
    
    protected $_listFeedsUrl;
    protected $_dataUrl;
    
    /**
     * Constructor for the class. Takes in user credentials and * generates the the authenticated client object.
     *
     * @param  string $email    The user's email address.
     * @param  string $password The user's password.
     * @return void
     */
    public function __construct( $email, $password, $service) {
        $client = Zend_Gdata_ClientLogin :: getHttpClient( $email, $password, $service);
        $this->gdClient = new Zend_Gdata( $client );
    }
    protected function __fetch($url) {
        $query = new Zend_Gdata_Query($url);
        $feed = $this->gdClient->getFeed($query);
        return $feed;
    }
    
    public function listFeeds() {
        return $this->__fetch($this->_listFeedsUrl);
    }
    
    public function fetchItems(array $params) {
        $url = $this->_dataUrl . '?' . http_build_query($params);
        return $this->__fetch($url);
    }
}

Now, we can use this parent class to create a class to work with Google Analytics:

<?php

class XXX_Google_Wrapper_Analytics extends XXX_Google_Wrapper_Abstract {
    protected $_listFeedsUrl = 'https://www.google.com' . '/analytics/feeds' . '/accounts/default';
    protected $_dataUrl = 'https://www.google.com' . '/analytics/feeds/data';
        
    public function __construct( $email, $password) {
        parent::__construct( $email, $password, 'analytics');
    }   
}

Both classes must be placed anywhere where your scripts can automatically load them. Zend Framework provides a simple naming convention to make it work automatically.

Google Analytics data is very flexible — e.g., you can grab total visits count, or visits of a page that contains a particular keyword in its URL. So we need one more abstract class, that we will use our Google Analytics wrapper to access any kind of required data:

<?php
abstract class Stats_Google_Analytics_Abstract {
    protected static
        $_wrapper,
        $_reportID;
    protected $_page;
        
    public function __construct() {
        
        if (!empty(self::$_wrapper)) return true;
        
        $config = Zend_Registry::get( 'config' ) -> toArray();
        $analyticsConfig = &$config[ 'google' ][ 'analytics' ];
        
        $email    = $analyticsConfig['email'];
        $password = $analyticsConfig['password'];
        self::$_reportID = $analyticsConfig['report']['id'];
        
        try {
            self::$_wrapper = new Sunny_Google_Wrapper_Analytics( $email, $password);
        }
        catch(Zend_Gdata_App_AuthException $e) {
            error_log( 'Zend_Gdata_App_AuthException: ' . $e->getMessage() );
            throw $e;
        }
    }
    
    public function fetchValue( $startDate, $endDate = null, array $additionalParams = null) {
        $list = $this->fetchAll( $startDate, $endDate, $additionalParams );
        $sum = array_sum($list);
        return $sum;
    }
    
    public function fetchAll($startDate, $endDate=null, array $additionalParams = null) {
        if (empty( $endDate )) {
            $endDate = $startDate;
        }
        $params = $additionalParams;
        $params['start-date']   = date('Y-m-d', strtotime( $startDate ));
        $params['end-date']     = date('Y-m-d', strtotime( $endDate ));
        $params['ids']          = self::$_reportID;
        
        try {
            $result = self::$_wrapper->fetchItems( $params );
        }
        catch(Exception $e) {
            error_log('Exception: ' . $e->getMessage());
            throw $e;
        }
        $dimensions = array();
        foreach ($result as $entry) {
            $extensions = $entry -> getExtensionElements();
            $attrs = array();
            foreach ($extensions as $extension) {
                $attributes = $extension -> getExtensionAttributes();
                $attrs[ $extension->rootElement ] = $attributes;
                $value  = $attributes[ 'value' ][ 'value' ];
                ${$extension -> rootElement} = $value;
            }
            
            if (empty($dimension)) {
                $dimension = null;
            }
            $dimensions[ $dimension ]  = $metric;
        }
        return $dimensions;
    }
    /**
     * Returns amount of unique visitors in the given time period
     * @param string $fromDate
     * @param string $toDate
     * @return int
     */
    public function count( $fromDate, $toDate = null) {
        $params = array(
            'metrics'       => 'ga:visits',
        );
        
        if (!empty($this->_page)) {
            $params['filters'] = 'ga:pagePath=~/'.$this->_page.'/*';
        }
        
        return $this->fetchValue( $fromDate, $toDate, $params );
    }
}
To make it work, your Zend Framework configuration file must include these settings:
google.analytics.email      = your@email.com
google.analytics.password   = YourPassword
google.analytics.report.id  = ga:12345
OK, all is ready. Let's create a class to grab statistics about all page views from your account:
<?php

//yes, it's an empty class since everything is defined in the abstract class
class Stats_Google_Analytics_Visit_Total extends Stats_Google_Analytics_Abstract {
}
$startDate = '2014-01-01';
$endDate = '2015-10-15';
$tracker = new Stats_Google_Analytics_Visit_Total;
echo $tracker->count( $startDate, $endDate );
This how to count pages that contain '/admin/' in their URL:
<?php

class Stats_Google_Analytics_Visit_Admin extends Stats_Google_Analytics_Abstract {

    protected $_page = 'admin';
}
$tracker = new Stats_Google_Analytics_Visit_Admin;
echo $tracker->count($startDate, $endDate);
As you can see, it's that easy!

Conclusion

This was the first of two parts of this article. Here we discussed how to grab data from your Google Analytics account for further processing, analyzing and display.

In the next part will be dedicated to sending data from PHP to Google Analytics since it can not only track accesses to your site Web pages, but with some extra work, it can also track your backend scripts load, like for example, your API usage.

If you liked this article so far, or you have questions about retrieving statistics from Google Analytics, post a comment here.




You need to be a registered user or login to post a comment

Login Immediately with your account on:

FacebookGmail
HotmailStackOverflow
GitHubYahoo


Comments:

1. Demo - Anthony Merzouki (2015-10-20 16:56)
Zip for demo ?... - 3 replies
Read the whole comment and replies



  Post a comment Post a comment   See comments See comments (4)   Trackbacks (0)  
  All package blogs All package blogs   PHP Google Analytics API Metrics Tracker PHP Google Analytics API Metrics Tracker   Blog PHP Google Analytics API Metrics Tracker package blog   RSS 1.0 feed RSS 2.0 feed   Blog Tracking PHP API Acce...