Wednesday, January 2, 2013

PHP code for Google Analytics API

I wanted to list the most popular documents during the last month within a specific directory on my website, using PHP calls to the Google Analytics API. There are several write-ups about this on the web, but here is my version.

First visit the Google API console and create a new project. You may choose any name. Enable Analytics API. Goto ”API access”. Click the button to ”Create an Oauth 2.0 client ID”. Choose any product ID. Click on “next”. Now comes the first important thing to remember: do not choose to create a webapp, instead choose to create a ”service account”. This will allow your app to login into your Google Analytics on it's own. Click create ”Client ID”. Click on ”Download private key”. You will get a .p12 file that you should put together with your php file you create later. Note the Client ID and the Email address you obtain now.

Now goto your Google Analytics pages and create a new user for the email address you just obtained. Give it administrator rights. Using this email as user, your php application will now have access to your Google Analytics data. Also note the profile ID number for your profile.

Download the google-api-php-client library from Google.

Time to code. Below are some pseudo code. There are 5 places you need to put your own data from the API console and your Google Analytics. Also change the filter if you want to narrow down the statistics to a specific directory. If you want to use the whole site, simple remove that line. The sample program will list the 5 most popular documents in the specified directory the last 30 days.

Example of usage can be seen at http://www.karinboye.se/index.shtml (in Swedish).

   
 // api dependencies  
   
 require_once('google-api-php-client/src/Google_Client.php');  
 require_once('google-api-php-client/src/contrib/
Google_AnalyticsService.php');  
   
 // create client object and set app name  
 $client = new Google_Client();  
 $client->setApplicationName('myapp'); // name of your app  
   
 // set assertion credentials  
 $client->setAssertionCredentials(  
   new Google_AssertionCredentials(  
     '000000000000@developer.gserviceaccount.com', // email to GA  
     array('https://www.googleapis.com/auth/analytics.readonly'),  
     file_get_contents('xxx-privatekey.p12') // keyfile   
   )  
 );  
   
 // other settings  
 $client->setClientId('000000000000.apps.googleusercontent.com'); 
// from API console  
 $client->setAccessType('offline_access'); 
   
 // create service and get data  
 $service = new Google_AnalyticsService($client);  
   
 $yesterday = date("Y-m-d", time() - (60*60*24) );  
 $monthago = date("Y-m-d", time() - (60*60*24*30) );  
   
 $response = $service->data_ga->get(  
     'ga:00000000', // profile id  
     $monthago, // start date  
     $yesterday, // end date  
     'ga:visitors',  
     array(  
       'dimensions' => 'ga:pagePath,ga:pageTitle',  
       'sort' => '-ga:visitors',  
       'filters' => 'ga:pagePath=~^/path/path/.*', // example url filter  
       'max-results' => '10'));  
   
 for ($i=0; $i<=9; $i++) {  
   
   $url = $response['rows'][$i][0];  
   $title = utf8_decode($response['rows'][$i][1]);  
   $visitors = $response['rows'][$i][2];  
   
   print "<a href=\"$url\">$title</a><br>";  
   
 }  
   

No comments:

Post a Comment