Google Analytics PHP5 界面总是无法显示结果

Google Analytics PHP5 Interface always fails to show result

我试图从我的 Google Analytics 帐户获取页面浏览量和访问量,所以我设置了一个这样的示例:https://code.google.com/p/gapi-google-analytics-php-interface/ 在我的本地主机上,但不知何故它没有返回任何内容.. .它总是失败。

这是我的代码(故意省略了密码和电子邮件):

<?php 
    require 'gapi.class.php';

    $gaEmail = 'email';
    $gaPassword = 'pass';
    $profileId = 'UA-37213064-1';

    $dimensions = array('pagePath','country', 'region', 'city'); 
    $metrics = array('visits');
    $sortMetric=null;
    $filter=null;
    $startDate='2011-02-01';
    $endDate='2015-01-30';
    $startIndex=1;
    $maxResults=10000;

    $ga = new gapi($gaEmail, $gaPassword);

    $ga->requestReportData($profileId, $dimensions, $metrics, $sortMetric, $filter,        $startDate, $endDate, $startIndex, $maxResults);

    $totalPageviews = $ga->getPageviews();

    foreach ($ga->getResults() as $result) {
       $visits = $result->getVists();
       print $visits; 
    }

?>

这里总是失败:

$ga = new gapi($gaEmail, $gaPassword);

错误:

PHP Fatal error:  Uncaught exception 'Exception' with message 'GAPI: Failed to authenticate user. Error: "Error=BadAuthentication
Url=https://www.google.com/accounts/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbttRRxx9DCBil669sL7kLRdff3nkCIN2ZZVwbU8erUozRAS9AUbn2wk7Rzjcotu7d3Hb7t3ihTxae_QFryWhZfF7uDfZDAL8GfF0w8CY8IopMZs9FEsmlkMlXczOKJ3QKLtEBGtPwCrjW69cI5U7NDe_WiPTWIZhXhf3znQjRU8TMrsNB6NNDMA_5zCwCMtTBYNB-tukpyRoFd3YS2HZfh4fJyDYA
Info=WebLoginRequired
"' in /Volumes/Macintosh Work/www/playground/gapi-1.3/gapi.class.php:418
Stack trace:
#0 /Volumes/Macintosh Work/www/playground/gapi-1.3/gapi.class.php(62): gapi->authenticateUser('Email...', 'password')
#1 /Volumes/Macintosh Work/www/playground/gapi-1.3/teste.php(17): gapi->__construct('EMAIL...', 'password')
#2 {main}
  thrown in /Volumes/Macintosh Work/www/playground/gapi-1.3/gapi.class.php on line 418

我几乎 100% 确定这不再有效。如果您检查一下,您会发现该项目自 2009 年以来就没有开发过,它允许您使用登录名和密码登录。客户端登录不适用于当前版本的 Google 分析,您必须使用开放式身份验证。

这取决于您在做什么,但您可以考虑使用 Php 客户端库。 https://github.com/google/google-api-php-client this will allow you to select your Google Analytics Data out using the Google Analytics API. You can find a tutorial here

您也可以考虑使用 Embeded API 这将允许您显示精美的图形及其 JavaScript 基础。

$analytics = new Google_Service_Analytics($client);

$profileId = 'UA-37213064-1';

$startDate='2011-02-01';
$endDate='2015-01-30';

$metrics = 'visits';

$optParams = array(
    'max-results' => 1000,
    'dimensions' => 'ga:pagePath,ga:country,ga:region,ga:city',         
);

$results = $analytics->data_ga->get('ga:'.$profileId, $startDate, $endDate, 'ga:'.$metrics, $optParams);

需要 - https://github.com/google/google-api-php-client

GAPI 2.0 版已发布,支持 OAuth2 和 Google Analytics API v3。您上面的代码可以工作,但 OAuth2 将要求您 create a 'service account' 然后下载一个 P12 文件以上传到服务器。最后你需要调整开发者控制台,启用'analytics API'。最后授予此新用户 'Read and Analyse' 对您要访问的 Google Analytics 帐户的权限。