Home > selvabalaji > Retrieving Google Analytics Data to Build a KPI Dashboard

Retrieving Google Analytics Data to Build a KPI Dashboard

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!
Categories: selvabalaji
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: