How to pull Google Analytics data from PHP using Google analytics API

08 January 2015 at 1:01pm 14 4 Samer
After Spending hours Trying to figure out how to pull Some Stats From Google Analytics and Reading allot of  blog posts/stackoverflow/github , I found this way to pull :D

if you are new to this hope this example can save you few hours.


Let's start with prerequisites for analytics service.

1. [GA_VIEW_ID] Find View ID for the website you want to pull data from.
​2. Create new API project [GA_APP_NAME] in google console:
​3. Enable Analytics API under APIs & auth > APIs > Analytics API.
​4. Create new client in Credentials section.
​​5. Download key file [GA_KEY_FILE_NAME] into your apps folder.
​​​6. In website analytics account User Management, add API Service account email address [GA_SERVICE_ACCOUNT_EMAIL] with read permissions. It should look something like:

First Thing Get the Google-Analytics-API-PHP for this Guy Github

save it somewhere in your website/app folder where you can include it

I've used his example to create this example. [ Save it ]
    * Basic usage example:  
    * - Redirect to the oAuth page if no access token is present  
    * - Handles the 'code' return from the oAuth page,  
    *  fetches an access token save it in a session variable  
    * - Makes an API request using the access token in the session var  
    * Make sure to request your API-key first at:   
   // From the APIs console  
   $client_id = '';  
   $email = '';  
   $privatekey = 'xxxxxxxxxxxxxxxx.p12';  
 $ga = new GoogleAnalyticsAPI('service');  
 $ga->auth->setClientId($client_id); // From the APIs console  
 $ga->auth->setEmail($email); // From the APIs console  
 $ga->auth->setPrivateKey($privatekey); // Path to the .p12 file  
    * Step 3: Do real stuff!  
    *     If we're here, we sure we've got an access token  
  $auth = $ga->auth->getAccessToken();  
 // Try to get the AccessToken  
 if ($auth['http_code'] == 200) {  
   $accessToken = $auth['access_token'];  
   $tokenExpires = $auth['expires_in'];  
   $tokenCreated = time();  
 } else {  
   echo "somthing went wrong";  
 $ga->setAccountId('ga:xxxxx'); // GA ID  
 // Load profiles  
 $profiles = $ga->getProfiles();  
 $accounts = array();  
 foreach ($profiles['items'] as $item) {  
   $id = "ga:{$item['id']}";  
   $name = $item['name'];  
   $accounts[$id] = $name;  
 // Print out the Accounts with Id => Name. Save the Id (array-key) of the account you want to query data.   
 // See next chapter how to set the account-id.  
   // Set the default params. For example the start/end dates and max-results  
   // Set the accessToken and Account-Id  
 $ga->setAccountId('ga:xxxxxx'); // GA ID  
 // Set the default params. For example the start/end dates and max-results  
 $defaults = array(  
   'start-date' => date('Y-m-d', strtotime('-3 month')), // get data of 3 months back  
   'end-date' => date('Y-m-d'),  
 echo "<br><br><br>Example1: Get visits by date <br><br><br>";  
 $params = array(  
   'metrics' => 'ga:visits',  
   'dimensions' => 'ga:date',  
 $visits = $ga->query($params);  
 echo "<br><br><br>Example2: Get visits by country<br><br><br>";  
 $params = array(  
   'metrics' => 'ga:visits',  
   'dimensions' => 'ga:country',  
   'sort' => '-ga:visits',  
   'max-results' => 30,  
   'start-date' => '2014-12-10' //Overwrite this from the defaultQueryParams  
 $visitsByCountry = $ga->query($params);  
 echo "<br><br><br> Example3: Same data as Example1 but with the built in method:<br> <br><br>";  
 $visits = $ga->getVisitsByDate();  
 echo "<br><br><br>Example4: Get visits by Operating Systems and return max. 100 results<br><br> <br>";  
 $visitsByOs = $ga->getVisitsBySystemOs(array('max-results' => 100));  
 echo "<br><br><br>Example5: Get referral traffic <br><br><br>";  
 $referralTraffic = $ga->getReferralTraffic();  
 echo " <br><br><br>Example6: Get visits by languages <br><br><br>";  
 $visitsByLanguages = $ga->getVisitsByLanguages();  

Change "XXXXXX" Parameters To your Site/Account one

if you run This example your get like 6 examples array ,

to know more about available Parameters of your Request check this
"This tool lets you play with the Core Reporting API by building queries to get data from your Google Analytics views (profiles). You can use these queries in any of the client libraries to build your own tools."

Reader Picture


There's a terrific amount of knwgoedle in this article!
2 years ago
Reader Picture


I don't know who you wrote this for but you helped a <a href="">brtoehr</a> out.
2 years ago
Reader Picture


It's posts like this that make surfing so much pleausre [url=]edtolnimwnc[/url] [link=]noomhzv[/link]
2 years ago
Reader Picture


I was drawn by the <a href="">hotnsey</a> of what you write
2 years ago
Comment has been Posted