在Google Analytics API v3 + PHP中按时间获取按时间顺序显示的数据/数据

时间:2019-04-15 11:58:30

标签: php time-series google-analytics-api

我正在使用CodeIgniter和Analytics v3 API PHP库。

编辑: 最初我使用的是jayaneetha/GoogleAnalytics-CodeIgniter ...该存储库对于初始CodeIgniter设置非常有用,但可能不如使用v4库)

我要完成的任务:为特定日期范围建立会话折线图;理想情况下是一个数组,因此我可以对其进行JSON编码。例如:

$ga_timeseries_data = (
  '2019-01-01' => 123,
  '2019-01-02' => 456,
  // ...
);

我所拥有的:该API可以设置并可以调用特定日期范围内的摘要指标。具体来说,返回的信息是指定范围内数据的总和。

我陷入困境的地方:如何通过API提取时间序列数据?我不想遍历日期并为每个日期发出API请求,因为我认为这样做会很慢。

我的代码:

function get_timeseries($type = 'sessions',$start_date, $end_date) {
   if ($this->access_token_ready) {
       $analytics = new Google_AnalyticsService($this->client);
       try {
           $optParams = array();
           $optParams['max-results'] = '5000';
           $results = $analytics->data_ga->get('ga:' . $this->ga_api_profileId, $start_date, $end_date, 'ga:' . $type, $optParams);
           return $results->getRows(); // This only outputs sum data.
       } catch (Exception $ex) {
           $error = $ex->getMessage();
           die($error);
       }
   }
}

1 个答案:

答案 0 :(得分:1)

经过一番摸索,我使用了v4 API,发现它更加健壮和简单。

本质上,我的错误是我需要使用date作为维度。

参考: Hello Analytics Reporting API v4; PHP quickstart for service accounts ...我修改了getReport函数以包含date维度,并将printResults修改为get_results

我的代码(请注意,这只是一个返回以'date'为维的数组的引用...即每个返回的数组项:date => sessions):

/**
 * 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 = "<REPLACE_WITH_VIEW_ID>";

  // Create the DateRange object.
  $dateRange = new Google_Service_AnalyticsReporting_DateRange();
  $dateRange->setStartDate("7daysAgo");
  $dateRange->setEndDate("today");

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

  //Create the Dimensions object. ## THIS IS WHAT I WAS MISSING##
  $browser = new Google_Service_AnalyticsReporting_Dimension();
  $browser->setName("ga:date");

  // Create the ReportRequest object.
  $request = new Google_Service_AnalyticsReporting_ReportRequest();
  $request->setViewId($VIEW_ID);
  $request->setDateRanges($dateRange);
  $request->setMetrics(array($sessions));

  $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.
 * ## I modified this because I didn't want to print results, rather I wanted to return an array ##
 */
 function get_results($reports) {
   $data = array();
   for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
     $report = $reports[ $reportIndex ];
     $header = $report->getColumnHeader();
     $dimensionHeaders = $header->getDimensions();
     $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
     $rows = $report->getData()->getRows();
     // ## NOTE: I've only done this with one metric/dimension...I'm not sure how well this holds up for multiple metrics/dimensions.
     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++) {
         $dimensions_arr[] = $dimensions[$i];
       }
       for ($j = 0; $j < count($metrics); $j++) {
         $values = $metrics[$j]->getValues();
         for ($k = 0; $k < count($values); $k++) {
           $metrics_arr[] = $values[$k];
         }

       }
     }
   }

   $data = array_combine($dimensions_arr,$metrics_arr);

   return $data;
 }