google php

ga api sample : get pageviews

I was going to put that online : how to get the pageviews out of the google analytics api, using simplexml and php. Google use three namespaces in the output file which make it less easy accessible, so here’s a quick sample of how to get your sites pageviews out of it :

//ids           = site identifier (from the site data feed)
//metrics     = what i want to see

$feedUri = ""; 			

	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $feedUri);
	curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 3);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

       $headers[] = "Authorization: GoogleLogin auth=".$Authtoken;

//for authtoken : see previous post
	curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); 
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl, CURLOPT_VERBOSE, 1);

//get the string containing the xml file
	$gA = curl_exec($curl);

the feed has three namespaces (atom, opensearch and dxp/analytics), a simple way is accessing the ENTRY tags (from the Atom namespace), in that tag is one DXP: line and that has the answer to the question.

<dxp:metric confidenceInterval=’0.0′ name=’ga:pageviews’ type=’integer’ value=’755’/>

//load the string into a simple xml object
	$feed = simplexml_load_string($gA);

//take the atom namespace
	$children =  $feed->children('');

//take the entry tags
	$parts = $children->entry;
	foreach ($parts as $entry) {

        //from the entry tag,
        //access the dxp namespace
		$dxp = (object) $entry->children('');

        //METRIC contains the answer to the question
        //grab from the tag METRIC the attribute VALUE
                echo   (string) $dxp->metric->attributes()->value;


Important is using the (string) typecast, normally simplexml returns a simplexml object, when you force a string type, it gives the actual metric ga:pageview value attribute as number.