June

23

Google Analytics Data Export API with Google Chart Visualizations

You can punch into the Google Analytics Data Export API, pull out some stats, and stuff them into some nice graphical charts using Google Chart Visualizations. This demo is done in PHP.
Google Chart Visualizations

Authenticate the User

The user can authenticate via the ClientLogin or using the AuthSub login which is actually more secure. For the ClientLogin, a typical username/password form is used. For the AuthSub login a link is used to send the user to Google to log in. Both are shown below. Normally you would use one or the other.

<form name="loginForm" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
		    <label for="email">Gmail:</label>
		    <input id="email" type="text" name="email" />
		    <label for="password">Password:</label>
		    <input type="password" name="password" id="password"/>
		    <br /><br />
		    <button type="submit" id="submitLogin">Submit</button>
		</form>
        <p><a class="button" href="https://www.google.com/accounts/AuthSubRequest?next=http://www.jensbits.com/demos/ga/app/&scope=https://www.google.com/analytics/feeds/&secure=0&session=1">Or,authenticate using AuthSub through Google.</a></p>

And, of course, the two authentication methods use different http calls to return a token that can be used to access the API.

//ClientLogin: try to log in and get session token for multiple API calls
if(isset($_POST['email']) && isset($_POST['password'])){
	$_SESSION['sessionToken'] = googleLogin($_POST['email'],$_POST['password']);
}
//AuthSub: exchange token for session token so multiple calls can be made to api
if(isset($_REQUEST['token'])){
	$_SESSION['authSub'] = true;
	$_SESSION['sessionToken'] = get_session_token($_REQUEST['token']);
}

//returns sessionToken for multiple calls to API
function googleLogin($email,$passwd){

    $clientlogin_url = "https://www.google.com/accounts/ClientLogin";
     $clientlogin_post = array(
    "accountType" => "GOOGLE",
    "Email" => $email,
    "Passwd" => $passwd,
    "service" => "analytics",
    "source" => "my-analytics"
	);

	$curl = curl_init($clientlogin_url);

	curl_setopt($curl, CURLOPT_POST, true);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $clientlogin_post);
	curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

	$response = curl_exec($curl);

	preg_match("/Auth=([a-z0-9_\-]+)/i", $response, $matches);
	$sessionToken = $matches[1];

	if (strlen($sessionToken) == 0){
		$sessionToken = "Authentication Failed.";
	}

 	return $sessionToken;
}

//AuthSub returns session token for multiple calls to API
	function get_session_token($onetimetoken) {
		$output = call_api($onetimetoken, "https://www.google.com/accounts/AuthSubSessionToken");

		if (preg_match("/Token=(.*)/", $output, $matches))
		{
			$sessionToken = $matches[1];
		} else {
			echo "Error authenticating with Google.";
			exit;
		}

		return $sessionToken;
	}

Data Requests

Once authenticated to a Google Analytics account and a multi-use session token is acquired, the data requests can be made. The first one will request the profiles (websites) associated with the account. If there is more than one, a dropdown select is populated allowing for the selection of the profile from which to pull data.

$accountxml = call_api($_SESSION['sessionToken'],"https://www.google.com/analytics/feeds/accounts/default");
// Get an array with the available accounts
$profiles = parse_account_list($accountxml);

The call_api function is going to return the XML data from Google based on the request URL sent in. In this case, it is getting the profile data and the parse_account_list function is rolling through that XML and putting the profile data in an array.

//gets the data
function call_api($sessionToken,$url){
	$curl = curl_init($url);

	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	if (isset($_SESSION['authSub'])){
		$curlheader[0] = sprintf("Authorization: AuthSub token=\"%s\"/n", $sessionToken);
	} else {
		$curlheader[0] = "Authorization: GoogleLogin auth=" . $sessionToken;
	}
	curl_setopt($curl, CURLOPT_HTTPHEADER, $curlheader);

	$response = curl_exec($curl);
	curl_close($curl);

	return $response;
}

//returns accounts list as array
function parse_account_list($xml){
	$doc = new DOMDocument();
	if(stripos($xml,"<") !== FALSE)
	{
		$doc->loadXML($xml);

		$entries = $doc->getElementsByTagName('entry');
		$i = 0;
		$profiles= array();
		foreach($entries as $entry)
		{
			$profiles[$i] = array();

			$title = $entry->getElementsByTagName('title');
			$profiles[$i]["title"] = $title->item(0)->nodeValue;

			$entryid = $entry->getElementsByTagName('id');
			$profiles[$i]["entryid"] = $entryid->item(0)->nodeValue;

			$tableId = $entry->getElementsByTagName('tableId');
			$profiles[$i]["tableId"] = $tableId->item(0)->nodeValue;

			$i++;
		}
		return $profiles;
	} else {
		$sessionToken = "Authentication Failed.";
	}

}

The dropdown of the profile array:

echo "<form name='siteSelect' id='siteSelect' method='post' action='" . $_SERVER['PHP_SELF'] . "'><p><label for='tableId'>Select Site:</label><select name='tableId' id='tableId'>";
		foreach($profiles as $profile)
		{
			if($profile["tableId"] == $table_Id)
				$selected = "selected='selected'";
				echo "<option value='" . $profile["tableId"] . "|" . $profile["title"] . "'" . $selected  . ">" . $profile["title"] . "</option>";
				$selected = " ";
		}
		echo "</select></p>";

The parse_data function below is going to roll through the data returned from Google Analytics and spit out an array that can be used to create the Google Visualization graphs.

//returns data as array
function parse_data($xml){
		$doc = new DOMDocument();
		$doc->loadXML($xml);

		$entries = $doc->getElementsByTagName('entry');
		$i = 0;
		$results = array();
		foreach($entries as $entry)
		{
			$countries[$i] = array();

			$dimensions = $entry->getElementsByTagName('dimension');
			foreach($dimensions as $dimension)
			{
				$results[$i][ltrim($dimension->getAttribute("name"),"ga:")] =  $dimension->getAttribute('value');
			}

			$metrics = $entry->getElementsByTagName('metric');
			foreach($metrics as $metric)
			{
				$results[$i][ltrim($metric->getAttribute('name'),"ga:")] =  $metric->getAttribute('value');
			}

			$i++;
		}
		return $results;
}

Graph Generation

Google Visualizations requires the inclusion of a javascript file in the head tag and empty div’s that will be the target for the graphs:

<script type="text/javascript" src="http://www.google.com/jsapi"></script>

The target div’s should be placed on the page where you want them to appear.

<div id='barchart_div'></div>
<div id='piechart_div'></div>

Finally, the data can be added to the chart generation javascript:

<script type="text/javascript">
      google.load("visualization", "1", {packages:["piechart"]});
      google.setOnLoadCallback(drawPieChart);
      function drawPieChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Referrer');
        data.addColumn('number', 'Visits');
        data.addRows(<?php echo sizeof($referrers) ?>);
        <?php
        $row = 0;
        foreach($referrers as $referrer)
		{
		?>
		data.setValue(<?php echo $row ?>,0,'<?php echo $referrer["source"] ?>');
		data.setValue(<?php echo $row ?>,1,<?php echo $referrer["visits"] ?>);
		<?php
		$row++;
		}
		?>

        var chart = new google.visualization.PieChart(document.getElementById('piechart_div'));
        chart.draw(data, {width: 600, height: 440, is3D: true, title: 'Referrer/Visits'});
	  	}

	  google.load("visualization", "1", {packages:["columnchart"]});
      google.setOnLoadCallback(drawBarChart);
      function drawBarChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Day');
        data.addColumn('number', 'Visits');
        data.addRows(<?php echo sizeof($visitsgraph) ?>);
		<?php
         $row = 0;
        foreach($visitsgraph as $visits)
		{
		?>
		data.setValue(<?php echo $row ?>,0,'<?php if ($visits_graph_type == "month"){echo date("M", mktime(0, 0, 0, $visits["month"]))." ".$visits["year"];}else{echo substr($visits['date'],6,2)."-".date('M', mktime(0, 0, 0, substr($visits['date'],4,2)))."-".substr($visits['date'],0,4);} ?>');
		data.setValue(<?php echo $row ?>,1,<?php echo $visits["visits"] ?>);
		<?php
		$row++;
		}
		?>
        var chart = new google.visualization.ColumnChart(document.getElementById('barchart_div'));
        chart.draw(data, {width: 700, height: 400, is3D: true, title: 'Visits'});
      }

    </script>

Recommended

Demo

Download zip of all files

No related posts.

8 Comments for Google Analytics Data Export API with Google Chart Visualizations


Gadget Newz
June 25, 2010

[...] Google Analytics Data Export API w/ Google Charts [...]

[...] This post was mentioned on Twitter by A.Elduayen, jkang. jkang said: New Post: Google Analytics Data Export API with Google Chart Visualizations on jensbits.com: http://bit.ly/aZo4nz [...]


Mark Schenkel
June 28, 2010

Nice post.

For those that are not "programmers", or are developing on non-php based platforms, we have developed a 3rd party web service which interfaces with the Google Analytics API and allows you to embed charts into websites. The benefit is it does not require any programming – you simply copy and past a snippet of code where the chart is to appear. The service is free to use. The site: http://www.embeddedanalytics.com


jen
June 29, 2010

@Mark
I took a look at your product. It is fine if people do not mind someone else, whoever that is, having their Google Anlaytics account log in information. I personally do not like turning over my credentials to a webservice and hoping that it is safe. With my own solution, I can control the security of my username and password.


Mark Schenkel
June 29, 2010

The service uses the AuthSub Authentication mechanism:
http://code.google.com/apis/accounts/docs/AuthSub.html

We never have access to your google account password. Rather we are granted a token (which can be revoked by the account owner at any time).

You could easily build this into your own solution.


jen
June 29, 2010

@Mark
I have used AuthSub and Secure AuthSub and there are examples of both on this site. I know how it works. You may not have a user's credentials, but you have full access to their data. This concerns me. When an application grabs the indefinite session auth token that is granted by the user and holds on to it, it has unlimited access to the user's GA stats. Ostensibly, once that session token is granted, an application can run any query against the GA account it wants. I understand it can be revoked, but once access is granted to an application outside of my servers, I am accepting an inherent risk.


Mark Schenkel
July 1, 2010

Well said. Totally understand.

It really comes down to trust and security. With EmbeddedAnalytics we are trying to build a reputation on both these facets.


Addon Solutions
August 6, 2010

Hi,

Its informative articles and we had checked that non-php embed script we are doing our self with XML for PHP want to know is there any one who did for iphone – Thanks

Leave a comment

Why ask?

 

« | »