如何访问Google Analytics数据?

时间:2012-05-29 10:37:02

标签: php

我的目标是在我网站的标题上显示Google Analytics数据。这就是我现在所拥有的一切(来自googleApiPhPClient / examples / analytics:

require_once 'library/GoogleApiPhpClient/apiClient.php';
$client = new apiClient();
$client->setApplicationName("Google Analytics PHP Starter Application");

// Visit https://code.google.com/apis/console?api=analytics to generate your
// client id, client secret, and to register your redirect uri.
 $client->setClientId('aaa');
 $client->setClientSecret('bbb_gK');
 $client->setRedirectUri('ccc');
 $client->setDeveloperKey('dd');

require_once ('contrib/apiAnalyticsService.php');
$service = new apiAnalyticsService($client);

if (isset($_GET['logout'])) {
  unset($_SESSION['token']);
}

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

if (isset($_SESSION['token'])) {
  $client->setAccessToken($_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>";
}

但这只会删除“连接我”链接。无论如何,我还能以正确的方式获得分析数据吗?

1 个答案:

答案 0 :(得分:1)

我一直在使用这个code.google.com/p/gapi-google-analytics-php-interface,它只需要谷歌帐户的用户名和密码,效果很好

a sample code of mine where im checking visits $ga->requestReportData($ga_profile_id,array('browser','browserVersion','country'‌​),array('pageviews','visits'),null,"country==USA",$yesterday,$todate); 

当您登录自己的帐户时,请选择您已为自己的网站制作的个人资料。当你点击它时,网址就像google.com/analytics/web/#report/visitors-overview / ...所以ga_profile_id将是在URL中“p”之后写的那个..我只看到这种方式获取此个人资料ID