Ryan Dorn
Ryan Dorn

Reputation: 797

Get Time-series / Data by Metric Over Time in Google Analytics API v3 + PHP

I'm using CodeIgniter and the Analytics v3 API PHP library.

EDIT: originally I was using jayaneetha/GoogleAnalytics-CodeIgniter...That repo is great for initial CodeIgniter setup, but is probably less favourable than using the v4 library)

What I want to accomplish: Build out a line chart of sessions for a specific date range; ideally as an array so I can JSON encode it. For example:

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

What I have: The API set up and able to call summary metrics for specific date ranges. Specifically, the returned information is a sum of the data for the specified range.

Where I'm getting stuck: How can I pull time-series data via the API? I don't want to loop through dates and make an API request for each date as I imagine that doing so would be slow.

My code:

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);
       }
   }
}

Upvotes: 3

Views: 967

Answers (1)

Ryan Dorn
Ryan Dorn

Reputation: 797

After a bit more poking around I used the v4 API, which I've found to be much more robust & straightforward.

Essentially, my mistake was that I needed to use date as a dimension.

Referencing: Hello Analytics Reporting API v4; PHP quickstart for service accounts...I modified the getReport function to include the date dimension and modified the printResults as get_results

My code (please note, this is just a reference to return an array with 'date' as a dimension...i.e. array items each returning: 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;
 }

Upvotes: 2

Related Questions