Retrieve Acquisition Overview & Top Channels Data Using Google Analytics Reporting API & PHP

In this post I’ll show you some code that will extract data from the Google Analytics Reporting API which is included on the Acquisition Overview page of the Google Analytics user interface. A specific report sometimes referred to as the Top Channels or Channel Grouping report (shown below) and contains some great traffic source comparison metrics like source, sessions, bounce rate, pages / session, session duration and goal completions and more.

Like my other posts on Google Analytics Reporting API, this example code does assume you have been able to connect to the API and authenticate to your account. You can find out more information about the Google APIs Client Library for PHP on their Github page.

If you would like a shortcut, click here to download the full working script files for a few bucks.

First, lets setup the query parameters, analytics account and date ranges using the below PHP code.

// Create the Analytics API object
$analytics = new Google_Service_Analytics($client);

// Define secondary parameters
$SecondaryParams = array('dimensions' => 'ga:channelGrouping');

// Setup and run the query to Analytics API
$sources = $analytics->data_ga->get(
 'ga:XXXXXXXX', // analytics view id, replace XXXXXXX with your ID
 '2018-06-01', // start date
 '2018-06-30', // end date
 'ga:sessions,ga:bounceRate,ga:goalCompletionsAll', 
 $SecondaryParams); // secondary parmas as defined above

I would suggest firstly trying to output the full API response using the PHP print_r() function, which allows you to trouble shoot any errors at this stage first.

Once you have the raw results showing from the API, I found the easiest way to access this data was to place it into an array, or a multi-dimensional array to be more accurate. In the below example, each row of source data (such as Organic Search, Referral etc) and the appropriate values are stored into the array for later use, like looping through and outputting or saving to a database.

// Create the array object
$sourcesresult = array();
 
// Loop through all the results using the total results returned value
for ($x = 0; $x < $sources['totalResults']; $x++) {

  // Add each source row into the array, with individual metics assigned within the same row
  $sourcesresult[] = array(
    'source' => $sources[$x][0],
    'sessions' => $sources[$x][1],
    'bounceRate' => $sources[$x][2],
    'goalCompletionsAll' => $sources[$x][3]
  );

}

Adding other metrics is pretty easy, simply consult the API reference page and either add or replace them on the below line. The below modified version of the above example will also return the Average Session Duration (ga:avgSessionDuration) and Page Views Per Session (ga:pageviewsPerSession).

'ga:sessions,ga:bounceRate,ga:goalCompletionsAll,ga:avgSessionDuration,ga:pageviewsPerSession',

Now that you have all your data in an array, we can store it in a mySQL database fairly easily. To do this and retain the array for later use, use the json_encode() function when inserting into your mySQL database.

INSERT INTO analytics (sourceresults) VALUES ('".json_encode($sourcesresult)."')";

Then when you come to retrieve this from the database on a different page, use the json_decode() function to make the array data usable again and then you can loop through this data and display in a nice table like below:

<table>
  <tr>
    <td><strong>Source</strong></td>
    <td><strong>Sessions</strong></td>
    <td><strong>Bounce Rate</strong></td>
    <td><strong>Goals</strong></td>
  </tr> 
  <?php
  $arr = json_decode($row['sources'], true);
  foreach ($arr as &$value) { 
  ?>
  <tr>
    <td><?php echo ucfirst($value['source']); ?></td>
    <td><?php echo $value['sessions']; ?></td>
    <td><?php echo number_format($value['bounceRate'],1); ?>%</td>
    <td><?php echo $value['goalCompletionsAll']; ?></td>
  </tr>
  <?
  }
  ?>
</table>

I hope this helps someone 🙂