Looping through the Google Analytics API PHP class data

Thanks for Jim Snyder from www.net-netanalytics.com for pointing out my examples were lacking the information to show how to loop through the resulting data from my Google Analytics API PHP Class. I have now update the examples file and also include the information about how to loop through the data in this post. You can always download the most recent version of my PHP class here.

The resulting array of data returned from the data() function is a multi dimensional array. The index(es) of the array are the dimensions passed in and then the value is another array with one vale for each of the metrics.

Looping through a single dimension

If, for example, you wanted to get the pagePath dimension and the pageviews and uniquePageviews metrics for pagePath, the data call would look like this:

$data = $api->data($id, 'ga:pagePath', 'ga:pageviews,ga:uniquePageviews');
 

You can then loop through the data like this:

foreach($data as $dimension => $metrics) {
     echo "$dimension pageviews: {$metrics['ga:pageviews']} unique pageviews: {$metrics['ga:uniquePageviews']}n";
 }
 

Looping through two dimensions

This example gets the browser and version as the dimensions and then visits and pageviews as the metrics. This requires an outer loop and an inner loop. The data call looks like this:

$data = $api->data($id, 'ga:browser,ga:browserVersion', 'ga:visits,ga:pageviews', false, false, false, 100);
 

The loop looks like this:

foreach($data as $dimension1 => $array) {
 foreach($array as $dimension2 => $metrics) {
         echo "$dimension1 $dimension2 visits: {$metrics['ga:visits']} pageviews: {$metrics['ga:pageviews']}n";
 }
 }
 

And some of the resulting output looks like this:

Internet Explorer 7.0 visits: 13486 pageviews: 16232
 Internet Explorer 6.0 visits: 4823 pageviews: 5932
 Internet Explorer 8.0 visits: 3047 pageviews: 3805
 Internet Explorer 999.1 visits: 15 pageviews: 15
 

You could also access the pageviews value directly for Internet Explorer 8 like this:

echo $data['Internet Explorer']['8.0']['ga:pageviews'], "n";
 
Categories PHP

Google Analytics PHP API: Getting data without a dimension

My Google Analytics API PHP class was initially developed assuming that a dimension would always be supplied but it doesn’t actually need to be, so I modified it to deal with no dimension and present an example here.

Thanks to Turner Walters from www.visionpointmarketing.com for pointing out this issue and helping with the solution.

If both a dimension (more more than one dimension) and a metric is supplied to the data() function then a multi-dimensional array is created storing the dimension(s) and metrics. I have now modified the function so that if there is no dimension then is a single dimensional array containing just the metric data instead.

This is useful if you want to get a summary for the account profile as a whole, instead of looking at data for specific dimensions.

For example, if you wanted to get an account overview for the last month showing counts for the number of bounces (i.e. one page only visits), new visitors, pageviews and unique pagesviews, you would do this:

$data = $api->data($id, '', 'ga:bounces,ga:newVisits,ga:visits,ga:pageviews,ga:uniquePageviews');

Doing print_r($data) would result in something along these lines:

Array
(
    [ga:bounces] => 80358
    [ga:newVisits] => 77986
    [ga:visits] => 91141
    [ga:pageviews] => 111634
    [ga:uniquePageviews] => 101403
)

You could then potentially loop through all the accounts in the class’s accounts array and get a summary for each account.

Categories PHP

Get the Google Analytics profile id from the accounts list

Just a quick post about an easy way to get the profile id for a Google Analytics account using my PHP Class. The ->load_accounts() function loads the accounts into an associative array which you can then access from ->accounts. The profile id is stored in there.

Here’s a code snippet illustrating this below, where we want to access data for the www.electrictoolbox.com profile:

$api = new analytics_api();
 if($api->login($login, $password)) {
 $api->load_accounts();
 $profile_id = $api->accounts['www.electrictoolbox.com']['tableId'];
 $data = $api->data($profile_id, ...);
 }
 

Alternatively you don’t need to store it in a separate variable and could do it like this instead:

$api = new analytics_api();
 if($api->login($login, $password)) {
 $api->load_accounts();
 $data = $api->data($api->accounts['www.electrictoolbox.com']['tableId'], ...);
 }
 

This uses my PHP class which can be downloaded here. More info and other posts about this here.

Categories PHP

PHP class for using the Google Analytics API

Just quickly following up my post from earlier on today where I looked at how to log into the Google Analytics API using PHP and CURL using Username/Password Authentication I wrapped the login code up into a class with methods for logging in and then calling API functions. I’ll look at parsing the XML result data at a later stage.

Update April 28th 2009: I’ve started a series about this. The full class, which I will continue to update over the next few days, can be downloaded here. The class presented below is an earlier version of it. Original post continues…

Here’s the class:

class analytics_api {
 
 protected $auth;
 
 public function login($email, $password) {
 
 $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin");
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_POST, true);
        
         $data = array(
             'accountType' => 'GOOGLE',
             'Email' => $email,
             'Passwd' => $password,
             'service' => 'analytics',
             'source' => ''
         );
        
         curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
         $output = curl_exec($ch);
         $info = curl_getinfo($ch);
         curl_close($ch);
        
         $this->auth = '';
         if($info['http_code'] == 200) {
             preg_match('/Auth=(.*)/', $output, $matches);
             if(isset($matches[1])) {
                 $this->auth = $matches[1];
             }
         }
        
         return $this->auth != '';
    
     }
    
     public function call($url) {
 
         $headers = array("Authorization: GoogleLogin auth=$this->auth");
        
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
         $output = curl_exec($ch);
         $info = curl_getinfo($ch);
         curl_close($ch);
 
         if($info['http_code'] == 200) {
             return $output;
         }
         else {
             return false;
         }
        
     }
    
 }
 

And here’s an example using it, calling https://www.google.com/analytics/feeds/accounts/default which gets a list of all the accounts that are available to view data for.

$api = new analytics_api();
 if($api->login('email@example.com', 'my-secret-password')) {
 $xml = $api->call('https://www.google.com/analytics/feeds/accounts/default');
 // ... process the xml ...
 }
 else {
 // login failed
 }
 

The class could easily be extended to parse the XML for common functions and have a function for getting the list of accounts into an array (or similar) and so on for other functions.

Update April 28th 2009: I’ve started a series about this and created a PHP class. The full class, which I will continue to update over the next few days, can be downloaded here.

Categories PHP