0

我在 PHP 中使用 Google Analytics Reporting API v4。

我想在另一个网页的仪表板上显示以下数据:30 天和 120 天的引荐来源网址和会话列表。

为此,我复制了 Web 服务器应用程序的 API 文档中提供的代码 ( https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/web-php ) 并进行了相关更改以获得提到的数据。

当我尝试独立检索数据以使用它来提供图表时,我的问题就出现了。

这是 Google Analytics Reporting API 代码,经过修改:

    // Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);


// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  // Set the access token on the client.
  $client->setAccessToken($_SESSION['access_token']);

  // Create an authorized analytics service object.
  $analytics = new Google_Service_AnalyticsReporting($client);

  // Call the Analytics Reporting API V4.
  $response = getReport($analytics); //see function below


} else {
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}


/**
 * Queries the Analytics Reporting API V4.
 *
 * @param service An authorized Analytics Reporting API V4 service object.
 * @return The Analytics Reporting API V4 response.
 */


 function getReport($analytics) {

  // Replace with your view ID, for example XXXX.
  $VIEW_ID = "888888888"; //View ID replaced 

  // Create the DateRange objects.
  $monthly = new Google_Service_AnalyticsReporting_DateRange();
  $monthly->setStartDate("30daysAgo");
  $monthly->setEndDate("today");

  $quarterly = new Google_Service_AnalyticsReporting_DateRange();
  $quarterly->setStartDate("120daysAgo");
  $quarterly->setEndDate("today");

  // Create the Metrics objects.
  $sessions = new Google_Service_AnalyticsReporting_Metric();
  $sessions->setExpression("ga:sessions");
  $sessions->setAlias("sessions");

  // Create the Dimensions object.
  $fullReferrer = new Google_Service_AnalyticsReporting_Dimension();
  $fullReferrer->setName("ga:fullReferrer");

  // Create the ReportRequest object.
  $request = new Google_Service_AnalyticsReporting_ReportRequest();
  $request->setViewId($VIEW_ID);
  $request->setDateRanges(array($monthly, $quarterly));
  $request->setMetrics(array($sessions));
  $request->setDimensions(array($fullReferrer));

  //Call the batchGet method.
  $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $body->setReportRequests( array( $request) );
  return $analytics->reports->batchGet( $body );

/**
 * Parses and prints the Analytics Reporting API V4 response.
 *
 * @param An Analytics Reporting API V4 response.
 */

function printResults($reports) {
  for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
    $report = $reports[ $reportIndex ];
    $header = $report->getColumnHeader();
    $dimensionHeaders = $header->getDimensions();
    $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
    $rows = $report->getData()->getRows();
    for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
      $row = $rows[ $rowIndex ];
      $dimensions = $row->getDimensions();
      $metrics = $row->getMetrics();
      for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
           $items_dim = array();
       foreach ($dimensions as $k =>$data){
            $items_dim[] = $data;
            }
            print_r($items_dim);  
      }

      for ($j = 0; $j < count($metrics); $j++) {
        $values = $metrics[$j]->getValues();
       for ($k = 0; $k < count($values); $k++) {
          $entry = $metricHeaders[$k];

            $items_val = array();           
            foreach ($values as $k =>$data){
            $items_val[] = $data;
          }
           print_r($items_val);
        }
      }
     }
  }
}

printResults($response->getReports());
   ?>

通过我所做的修改,我设法从

    printResults($response->getReports());

看起来像一个数组:

数组 ( [0] => (direct) ) 数组 ( [0] => 20 ) 数组 ( [0] => 168 ) 数组 ( [0] => url1 ) 数组 ( [0] => 0 ) 数组 ( [ 0] => 3 ) 数组 ( [0] => url2 ) 数组 ( [0] => 0 ) 数组 ( [0] => 3 ) 数组 ( [0] => url3 ) 数组 ( [0] => 0 ) 数组 ( [0] => 11 ) 数组 ( [0] => url4 ) 数组 ( [0] => 0 ) 数组 ( [0] => 3 ) ...

[0] 引用会话对象。有三个项目:

  • 网址。
  • 30 天的会议。
  • 120天的会议。

所以问题是如何从函数的结果中检索数据,以便可以独立使用它来提供图表

到目前为止,我尝试将函数存储在变量 $results 中,这样我就可以遍历数组,但它不起作用:

$results = printResults($response->getReports());
print ($results);

上面的代码打印一次结果。

$results = printResults($response->getReports());
//print ($results);

上面的代码也打印了一次结果,所以工作是由 pintResults() 函数完成的,而不是由 print() 完成的。

我还尝试在定义函数时将其存储在变量 $results 中(都不工作):

$results = function printResults($reports) {
  for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
    $report = $reports[ $reportIndex ];
    $header = $report->getColumnHeader();
    ...
4

0 回答 0