php - Google Analytics Data Export API V3


I am trying to get to grips with interacting with the GA API v3 using php. Being quite new to php, I am struggling somewhat. Does anyone here have any experience with using the api with php (v3)?

Google does supply a small sample script but it's effectively useless (with my limited skills) as it returns an api key but doesn't tell you where it needs to go or why you need it.

If anyone has any knowledge I would be very grateful if you could show me how.




You need to make sure you register you API with Google from their API console. Make sure you turn on Google Analytics, and create a project.

After make sure you download the full api from Google Code.

You want to go into simple.php located in the Analytics folder (under examples) and uncomment lines 11-14, and replace with information from Google API Console:


This will let you connect and you will see the basic data. For more details and a great tutorial you can see it here.

Your total page should look like this:

require_once '../../src/apiClient.php';
require_once '../../src/contrib/apiAnalyticsService.php';

$client = new apiClient();
$client->setApplicationName("Google Analytics PHP Starter Application");

// Visit to generate your
// client id, client secret, and to register your redirect uri.
$service = new apiAnalyticsService($client);

if (isset($_GET['logout'])) {

if (isset($_GET['code'])) {
  $_SESSION['token'] = $client->getAccessToken();
  header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);

if (isset($_SESSION['token'])) {

if ($client->getAccessToken()) {

  $props = $service->management_webproperties->listManagementWebproperties("~all");
 print "<h1>Web Properties</h1><pre>" . print_r($props, true) . "</pre>";

  $accounts = $service->management_accounts->listManagementAccounts();
  print "<h1>Accounts</h1><pre>" . print_r($accounts, true) . "</pre>";

  $segments = $service->management_segments->listManagementSegments();
  print "<h1>Segments</h1><pre>" . print_r($segments, true) . "</pre>";

  $goals = $service->management_goals->listManagementGoals("~all", "~all", "~all");
 print "<h1>Segments</h1><pre>" . print_r($goals, true) . "</pre>";

  $_SESSION['token'] = $client->getAccessToken();
} else {
  $authUrl = $client->createAuthUrl();
  print "<a class='login' href='$authUrl'>Connect Me!</a>";

People are also looking for solutions to the problem: php - I get duplicate error when I post same string using NameValuePair


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.