Skip to content

Instantly share code, notes, and snippets.

@davebarnwell
Last active March 26, 2016 21:48
Show Gist options
  • Select an option

  • Save davebarnwell/7d495fbf4c455fb214cf to your computer and use it in GitHub Desktop.

Select an option

Save davebarnwell/7d495fbf4c455fb214cf to your computer and use it in GitHub Desktop.
Connect to google analytics using the google php client and a service account key
<?php
/**
* include via composer Google client lib
* composer require google/apiclient:^2.0.0@RC
* include the autoload.php
*
* Create a service account key in the google developer console
* and download the key file into your project above the web root somewhere
*/
require_once '/path/to/your-project/vendor/autoload.php';
/**
* @return Google_Service_Analytics
* @throws Exception
*/
function getAnalyticsInstance()
{
// Creates and returns the Analytics service object.
// Use the developers console and replace the values with your
// service account email, and relative location of your key file.
$key_file_location = 'key_download_from_developer_console.json';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName('My GA app');
$analytics = new Google_Service_Analytics($client);
// Read the generated client_secrets key
$client->setAuthConfig($key_file_location);
$scopes = [Google_Service_Analytics::ANALYTICS_READONLY];
$client->setScopes($scopes);
if ($client->isAccessTokenExpired()) {
$client->refreshTokenWithAssertion();
}
return $analytics;
}
$analytics = getAnalyticsInstance();
$fromDate = '2016-01-01';
$toDate = '2016-01-07';
$results = $analytics->data_ga->get(
'ga:{your_google_analytics_profile_id_to_be_queried}',
$fromDate,
$toDate,
'ga:bounceRate,ga:avgSessionDuration,ga:sessions,ga:users,ga:newUsers'
);
$ga = [];
if ($results && ($rows = $results->getRows())) {
foreach ($rows as $row) {
// rows numerically index order as requested in call
$ga = array(
'bounceRate' => (float)$row[0],
'avgSessionDuration' => (float)$row[1],
'sessions' => (int)$row[2],
'users' => (int)$row[3],
'newUsers' => (int)$row[4]
);
// dump output
var_dump($ga);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment