Using PHP with Google Analytics API

Posted by Nethab at 5:35 PM

Since Google Analytics just released their API as a public beta, I decided to try and get it working with the PHP Zend GData library. I've seen several implementations using cURL, but the GData library seems ready-made for it, so I figured why not save some hassle.

Logging In

The first thing you have to do is login to the API service.

$email = "<email@domain.com>"; $pass = "<password>"; require_once("Zend/Loader.php"); Zend_Loader::loadClass('Zend_Gdata'); Zend_Loader::loadClass('Zend_Gdata_Query'); Zend_Loader::loadClass('Zend_Gdata_ClientLogin'); $client = Zend_Gdata_ClientLogin::getHttpClient($email, $pass, "analytics"); $gdClient = new Zend_Gdata($client);

List of Accounts/Profiles

Now that we've logged in, we need to get a list of available Accounts/Profiles. Specifically we need to get the "profile ID" of the website we want to report on.

try { $results = $gdClient->getFeed("https://www.google.com/analytics/feeds/accounts/$email"); foreach ($results as $entry) { echo "Profile: " . $entry->title . " - Id: " . $entry->extensionElements[0] . "\n"; } } catch (Zend_Exception $e) { echo "Caught exception: " . get_class($e) . "\n"; echo "Message: " . $e->getMessage() . "\n"; }

Fetching the Data

Now that we've found our profile ID, we should decide which data we want to collect, and request it from Google's servers. I find it easiest to return it as CSV.

try { $dimensions = array("ga:region", "ga:city", "ga:latitude", "ga:longitude"); $metrics = array("ga:visits", "ga:pageviews"); $reportURL = "https://www.google.com/analytics/feeds/data?ids=<profile ID>&" . "dimensions=" . @implode(",", $dimensions) . "&" . "metrics=" . @implode(",", $metrics) . "&" . "start-date=<YYYY-MM-DD>&" . "end-date=<YYYY-MM-DD>"; $results = $gdClient->getFeed($reportURL); $titleRow = 1; // To output a row of column labels foreach ($results as $rep) { if ($titleRow) { foreach ($rep->extensionElements as $elem) { $titles[] = $elem->extensionAttributes["name"]["value"]; } echo implode(",", $titles) . "\n"; $titleRow = 0; } foreach ($rep->extensionElements as $elem) { $row[] = $elem->extensionAttributes["value"]["value"]; } echo implode(",", $row) . "\n"; } } catch (Zend_Exception $e) { echo "Caught exception: " . get_class($e) . "\n"; echo "Message: " . $e->getMessage() . "\n"; }


Labels: , ,

Subscribe to: Posts (Atom)