Accessing Google Analytics with Google Client API and PHP tutorial

This article describes step by step how you can access Google Analytics with the Google Client API and PHP. If you haven’t read the Google Client API article, please do it now and set up the environment.

Goal

Extract the usage data from Google Analytics for a domain you have access to.

Step 1: Access Google Analytics with Google Client API

The result of the article Google Client API – step by step tutorial is the foundation of step one. We now ask Google Analytics to give us a list of all available domains we have access to with the used Google user account.

Update the script, so that it looks like:

<?php
session_start();
require_once dirname(__FILE__).'/GoogleClientApi/Google_Client.php';
require_once dirname(__FILE__).'/GoogleClientApi/contrib/Google_AnalyticsService.php';

$scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];

$client = new Google_Client();
$client->setAccessType('online'); // default: offline
$client->setApplicationName('My Application name');
$client->setClientId('INSERT HERE');
$client->setClientSecret('INSERT HERE');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('INSERT HERE'); // API key

// $service implements the client interface, has to be set before auth call
$service = new Google_AnalyticsService($client);

if (isset($_GET['logout'])) { // logout: destroy token
    unset($_SESSION['token']);
	die('Logged out.');
}

if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
    $client->authenticate();
    $_SESSION['token'] = $client->getAccessToken();
}

if (isset($_SESSION['token'])) { // extract token from session and configure client
    $token = $_SESSION['token'];
    $client->setAccessToken($token);
}

if (!$client->getAccessToken()) { // auth call to google
    $authUrl = $client->createAuthUrl();
    header("Location: ".$authUrl);
    die;
}

try {
    $props = $service->management_webproperties->listManagementWebproperties("~all");
    echo '<h1>Available Google Analytics projects</h1><ul>'."\n";
    foreach($props['items'] as $item) printf('<li>%1$s</li>', $item['name']);
    echo '</ul>';
} catch (Exception $e) {
    die('An error occured: ' . $e->getMessage()."\n");
}

When accessing the script with your browser, you should now see a list of domains from your Google Analytics account.

Step 2: Extracting the visitor numbers from Google Analytics

As it’s written here, you need a special ID to access the measures and values for your domain. Unfortunately there is no API call for this. So you need to open your browser, access an Analytics report for this domain and extract the number from the URL. If you read the URL carefully, it will contain a string like a123w456p7890 – you need the number after p:

Add the following code to your test script and change $projectId to the appropriate value.

$projectId = '12345';

// metrics
$_params[] = 'date';
$_params[] = 'date_year';
$_params[] = 'date_month';
$_params[] = 'date_day';
// dimensions
$_params[] = 'visits';
$_params[] = 'pageviews';
$_params[] = 'bounces';
$_params[] = 'entrance_bounce_rate';
$_params[] = 'visit_bounce_rate';
$_params[] = 'avg_time_on_site';

$from = date('Y-m-d', time()-2*24*60*60); // 2 days
$to = date('Y-m-d'); // today

$metrics = 'ga:visits,ga:pageviews,ga:bounces,ga:entranceBounceRate,ga:visitBounceRate,ga:avgTimeOnSite';
$dimensions = 'ga:date,ga:year,ga:month,ga:day';
$data = $service->data_ga->get('ga:'.$projectId, $from, $to, $metrics, array('dimensions' => $dimensions));

foreach($data['rows'] as $row) {
   $dataRow = array();
   foreach($_params as $colNr => $column) echo $column . ': '.$row[$colNr].', ';
}

When you now access the script again with your browser, you should see some stats.

There are a lot of fields available. Google calls them metrics and dimensions – terms used in data warehouse.

The first step is done, now you can extend this simple demo script and adapt it to your needs. Check out the ressources and links in the further reading section.

Try the live demo for Google Analytics API

Download the source code at https://github.com/tobiaskluge/enarionGoogPhp.

Further reading