Using Google Analytics Reporting API & PHP to Retrieve Metrics Like Sessions, Hits, Bounce Rate, Goals

In this example we will use the Google Analytics Reporting API and PHP to extract some basic website performance metrics such as total sessions, hits, bounce rate, session duration, goal conversions and conversion rate for a month long date range. Basically the metrics displayed on the Audience Overview page within the Analytics interface.

The below example code does assumes you have been able to connect to the Google Analytics API and authenticate to your account. I found this to be the most time consuming and detailed part of this process. 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.

You will need one piece of information from your Google Analytics account to run these queries and that is the analytics view id, which can be found at the bottom most, view level of Google Analytics, shown below:

Simply replace the ga:XXXXXXXX in the below script with your own view ID and off you go.

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

// Setup and run the query to Analytics API
$generalstats = $analytics->data_ga->get(
 'ga:XXXXXXXX', // analytics view id
 '2018-06-01', // start date
 '2018-06-30', // end date
 'ga:users,ga:sessions,ga:hits,ga:pageviewsPerSession,ga:avgSessionDuration,ga:bounceRate,ga:goalCompletionsAll,ga:goalConversionRateAll'); //

I would suggest firstly trying to output the full API responce using the PHP print_r() function (shown below), which allows you to trouble shoot any errors.

// Output all API results
echo '<pre>';
print_r($generalstats);
echo '</pre>';

Once you have the results showing up, you can use the below code to isolate each metric into a variable for later use such as inserting into an SQL database or similar.

// Extract the data into variables for later use
$users = $generalstats[0][0]; 
$session = $generalstats[0][1];
$hits = $generalstats[0][2];
$pageviewsPerSession = $generalstats[0][3];
$avgSessionDuration = $generalstats[0][4];
$bounceRate = $generalstats[0][5];
$goalCompletionsAll = $generalstats[0][6];
$goalConversionRateAll = $generalstats[0][7];

You may have noticed that the above isolates each returned metric via a number ([0][1],[0][2],etc,etc), which is the same order that the query part of the request (ga:users,ga:sessions,ga:hits,etc,etc) has been set.

There are many more possible metrics which can be returned, and a great reference for these is the Analytics API Dimensions & Metrics Explorer.

I hope this article is helpful to someone out there building something cool.