Google’s PHP client library for their GData API hasn’t received as much love as their client libraries for other languages. Despite the lack of high level service classes for Google Analytics’ Core Reporting API it is possible to work with it using google-api-php-client.
The below is a quick and dirty self contained example based on a Google+ example to get a report. Before you get started go to the API Console and enable access to the Analytics API and generate a client id, client secret, and to register your redirect uri.
As a bonus, this example also shows you how to get page views per day over the last two weeks. I spent the better part of a day finding this incantation, so Merry Christmas PHP Developers!
<?php $ga_ua = 'UA-XXXXXXX-X'; // This is the ID from your GA snippet. $client_id = 'your client id'; // From the API Console $client_secret = 'your client secret'; // From the API Console $redirect_url = 'http://yourdomain.com/ga-gdata.php'; // The address of this script require_once 'path/to/google-api-php-client/src/apiClient.php'; session_start(); $client = new apiClient(); $client->setScopes('https://www.googleapis.com/auth/analytics.readonly'); $client->setApplicationName("GA Report"); $client->setClientId($client_id); $client->setClientSecret($client_secret); $client->setRedirectUri($redirect_url); if (isset($_GET['logout'])) { unset($_SESSION['token']); header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']); } if (isset($_GET['code'])) { if (strval($_SESSION['state']) !== strval($_GET['state'])) { die("The session state ({$_SESSION['state']}) didn't match the state parameter ({$_GET['state']})"); } $client->authenticate(); $_SESSION['token'] = $client->getAccessToken(); header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']); } if (isset($_SESSION['token'])) { $client->setAccessToken($_SESSION['token']); } if ($client->getAccessToken()) { $url = 'https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties/~all/profiles'; $request = $client->getIo()->authenticatedRequest(new apiHttpRequest($url)); if ($request->getResponseHttpCode() != 200) { throw new apiException("http code: " . $request->getResponseHttpCode() . ", response body: " . $request->getResponseBody()); } $json = json_decode($request->getResponseBody(), true); foreach ($json['items'] as $item) { if ($item['webPropertyId'] == $ga_ua) { $web_property_id = $item['id']; } } $yesterday = strtotime('-1 day'); $two_weeks_ago = strtotime('-2 weeks', $yesterday); $search_config = array( 'ids' => 'ga:'.$web_property_id, 'start-date' => date('Y-m-d', $two_weeks_ago), 'end-date' => date('Y-m-d', $yesterday), 'dimensions' => 'ga:year,ga:month,ga:day', 'metrics' => 'ga:pageviews' ); $url = 'https://www.googleapis.com/analytics/v3/data/ga?'.http_build_query($search_config); $request = $client->getIo()->authenticatedRequest(new apiHttpRequest($url)); if ($request->getResponseHttpCode() != 200) { throw new apiException("http code: " . $request->getResponseHttpCode() . ", response body: " . $request->getResponseBody()); } echo '<pre>'; var_dump(json_decode($request->getResponseBody(), true)); // The access token may have been updated lazily. $_SESSION['token'] = $client->getAccessToken(); } else { $state = mt_rand(); $client->setState($state); $_SESSION['state'] = $state; $authUrl = $client->createAuthUrl(); print "<a class='login' href='$authUrl'>Connect Me!</a>"; }
Tags: google, google analytics, Google API






Thanks for your example … but I could get only one of my accounts at the time… and I tried to find a way to get access to all of my accounts i.e. each table/ web site which is controlled in my account.
It is needed profileId which I could get with a piece of your code – still complicated (referring to my code) but at the end I found a solution using apiAnalyticsService.php (the example is on http://code.google.com/p/google-api-php-client/source/browse/trunk/examples/analytics/simple.php and if you add just a piece of code below to get profileId for each table (ids):
$profiles=$service->management_profiles->listManagementProfiles(“~all”, “~all”);
print “Profiles
“;
and then you can use another piece of code to process data:
$data = $service->data_ga->get($ids, $start_date, $end_date, $metrics, $optParams);
print “Data
“;
Thanks for the feedback Tereza, I’m sure it will be helpful to someone.