php - Google Analytics 核心报告 API PHP 查询

标签 php analytics google-analytics-api

这是我第一次尝试使用 Core Reporting API。我已成功完成 Hello Analytics 教程并毫无问题地发出 API 请求。我的问题在于查询 API 以使用维度、指标和过滤器。下面是我正在使用的代码。我能够显示从本月第一天到当天我有多少访客。然后它会显示其中有多少来自有机搜索。我希望有人能给我一个关于使用更复杂的请求查询 API 的示例……可能包括维度、指标、过滤器……然后按行显示。任何帮助深表感谢。到目前为止,下面是我的代码...

//查询核心报告API

    function getResults($analytics, $profileId, $first_day, $today) {
         return $analytics->data_ga->get(
    'ga:' . $profileId,
    $first_day,
    $today,
    'ga:visits, ga:organicSearches');
    }

//输出结果

    function printResults(&$results) {
          if (count($results->getRows()) > 0) {
    $profileName = $results->getProfileInfo()->getProfileName();
    $rows = $results->getRows();
    $visits = $rows[0][0];
    $organic = $rows[0][1];
    print "<h1>$profileName</h1>";

    echo '<table border="1" cellpadding="5">';

   echo '<tr>';
   echo '<td>Visits</td>';
   echo '<td>Organic</td>';
   echo '</tr>';

   echo '<tr>'; 
   echo '<td>'. $visits . '</td>';
   echo '<td>'. $organic . '</td>';   
   echo '</td>';

   echo '</table>';

   } else {
        print '<p>No results found.</p>';
   }
}

最佳答案

代码如下:

$optParams = array(
        'dimensions' => 'ga:date,ga:customVarValue1,ga:visitorType,ga:pagePath',
        'sort' => '-ga:visits,ga:date',
        'filters' => 'ga:visitorType==New',
        'max-results' => '100');

$metrics = "ga:visits";
$results = $analytics->data_ga->get(
'ga:' . $profileId,
'2013-03-01',
'2013-03-10',
$metrics,
$optParams);

用于显示结果:

 function getRows($results) {
      $table = '<h3>Rows Of Data</h3>';

      if (count($results->getRows()) > 0) {
      $table .= '<table>';

      // Print headers.
      $table .= '<tr>';

      foreach ($results->getColumnHeaders() as $header) {
          $table .= '<th>' . $header->name . '</th>';
      }
      $table .= '</tr>';

      // Print table rows.
      foreach ($results->getRows() as $row) {
        $table .= '<tr>';
        foreach ($row as $cell) {
           $table .= '<td>'
               . htmlspecialchars($cell, ENT_NOQUOTES)
               . '</td>';
        }
        $table .= '</tr>';
      }
      $table .= '</table>';

      } else {
      $table .= '<p>No results found.</p>';
      }

      return $table;
  }

如果你尝试得到这个demo,你会更好地理解工作。
另请参阅此 code

关于php - Google Analytics 核心报告 API PHP 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11968769/

相关文章:

google-analytics - 我想要一个使用 orderBy 和 Filters 的 PHP 中 Google Analytics Data API (GA4) 的示例代码

google-analytics - Google Analytics API - 指标的选择会影响返回的维度值吗?

javascript - 在 WP 中使用 PHP 将 javascript 字符串插入 HTML

logging - 从PHP应用程序记录页面请求数据的可扩展方式?

php - 从我的用户数据中使用图表、 map 等进行可视化分析?

javascript - Google Analytics - 追踪 404 referer

javascript - 如何可靠地获取 Google Analytics 生成的 session ID?

php - 连接两个表时出现 "Message : Undefined Variable:query "错误 codeigniter mysql php

javascript - PHP 结果到 AJAX 比较数组问题

php - Sql 多链表