Search code examples
phpgoogle-analytics-apisegmentgoogle-apis-explorergoogle-reporting-api

How to get data on hourly basis for two days? (Google Analytics Reporting API v4, PHP library)


I need to have report metrics on hourly basis in time period passing midnight. For example, starting at 20:00 and ending at 03:00. To do this I set date range where StartDate is 'yesterday' and EndDate is 'today':

$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate('yesterday');
$dateRange->setEndDate('today');

And to retrieve data on hourly basis I harnessed two segments. One is for the data before midnight (for example, 20:00 to 23:59) and another is for the data after midnight (for example, 00:00 to 03:00). In JSON request the segment looks something like this: sessions::condition::ga:hour<>20_23,ga:hour<>00_03:

https://support.google.com/analytics/answer/7331978?hl=en

Below is my code for the request with some dimension and metric filters (that is, I am requesting amount of page views from users being on a page more than 8 seconds, title of which contains word: 'portfolio'):

// How to create $client you can read in Google Analytics documentation
$analytics = new Google_Service_AnalyticsReporting($client);

// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate('yesterday');
$dateRange->setEndDate('today');

// Create the Metrics object.
$metrics = new Google_Service_AnalyticsReporting_Metric();
$metrics->setExpression('ga:pageviews');

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

// Create the DimensionFilter.
$dimensionFilter = new Google_Service_AnalyticsReporting_DimensionFilter();
$dimensionFilter->setDimensionName('ga:pageTitle');
$dimensionFilter->setOperator('PARTIAL');
$dimensionFilter->setExpressions(['portfolio']);

// Create the MetricFilter.
$metricFilter = new Google_Service_AnalyticsReporting_MetricFilter();
$metricFilter->setMetricName('ga:timeOnPage');
$metricFilter->setOperator('GREATER_THAN');
$metricFilter->setComparisonValue('8');

// Create the DimensionFilterClauses
$dimensionFilterClause = new 
Google_Service_AnalyticsReporting_DimensionFilterClause();
$dimensionFilterClause->setFilters($dimensionFilter);
$request->setDimensionFilterClauses(array($dimensionFilterClause));

// Create the MetricFilterClauses
$metricFilterClause = new 
Google_Service_AnalyticsReporting_MetricFilterClause();
$metricFilterClause->setFilters($metricFilter);
$request->setMetricFilterClauses([$metricFilterClause]);

// Creating multiple segments with function createSegment()
$segments = [];
$segments[] = createSegment('15', '23', 'Before Midnight');
$segments[] = createSegment('00', '10', 'After Midnight');

//Create the hour dimension.
$hour = new Google_Service_AnalyticsReporting_Dimension();
$hour->setName("ga:hour");

// Create the segment dimension.
$segmentDimensions = new Google_Service_AnalyticsReporting_Dimension();
$segmentDimensions->setName("ga:segment");

// Set the Segment to the ReportRequest object.
$request->setDimensions(array($hour, $segmentDimensions));
$request->setSegments($segments);

// Get report request
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests(array($request));
$report = $analytics->reports->batchGet($body);
$reports = $report->getReports();

function createSegment($min, $max, $name) {

    // Set a segment for hourly time range. For daily time range there is no neen id a segment.
    $dimensionFilter = new Google_Service_AnalyticsReporting_SegmentDimensionFilter();
    $dimensionFilter->setDimensionName('ga:hour');
    $dimensionFilter->setOperator('NUMERIC_BETWEEN');

    // $dimensionFilter->setExpressions($alert->get_expressions());
    $dimensionFilter->setMinComparisonValue($min);
    $dimensionFilter->setMaxComparisonValue($max);

    // Create Segment Filter Clause.
    $segmentFilterClause = new Google_Service_AnalyticsReporting_SegmentFilterClause();
    $segmentFilterClause->setDimensionFilter($dimensionFilter);

    // Create the Or Filters for Segment.
    $orFiltersForSegment = new Google_Service_AnalyticsReporting_OrFiltersForSegment();
    $orFiltersForSegment->setSegmentFilterClauses(array($segmentFilterClause));

    // Create the Simple Segment.
    $simpleSegment = new Google_Service_AnalyticsReporting_SimpleSegment();
    $simpleSegment->setOrFiltersForSegment(array($orFiltersForSegment));

    // Create the Segment Filters.
    $segmentFilter = new Google_Service_AnalyticsReporting_SegmentFilter();
    $segmentFilter->setSimpleSegment($simpleSegment);

    // Create the Segment Definition.
    $segmentDefinition = new Google_Service_AnalyticsReporting_SegmentDefinition();
    $segmentDefinition->setSegmentFilters(array($segmentFilter));

    // Create the Dynamic Segment.
    $dynamicSegment = new Google_Service_AnalyticsReporting_DynamicSegment();
    $dynamicSegment->setSessionSegment($segmentDefinition);
    $dynamicSegment->setName($name);

    // Create the Segments object.
    $segment = new Google_Service_AnalyticsReporting_Segment();
    $segment->setDynamicSegment($dynamicSegment);

    return $segment;
}

You can see response from the request below:

Google_Service_AnalyticsReporting_GetReportsResponse Object
(
[collection_key:protected] => reports
[queryCost] => 
[reportsType:protected] => Google_Service_AnalyticsReporting_Report
[reportsDataType:protected] => array
[resourceQuotasRemainingType:protected] => Google_Service_AnalyticsReporting_ResourceQuotasRemaining
[resourceQuotasRemainingDataType:protected] => 
[internal_gapi_mappings:protected] => Array
    (
    )

[modelData:protected] => Array
    (
        [reports] => Array
            (
                [0] => Google_Service_AnalyticsReporting_Report Object
                    (
                        [columnHeaderType:protected] => Google_Service_AnalyticsReporting_ColumnHeader
                        [columnHeaderDataType:protected] => 
                        [dataType:protected] => Google_Service_AnalyticsReporting_ReportData
                        [dataDataType:protected] => 
                        [nextPageToken] => 
                        [internal_gapi_mappings:protected] => Array
                            (
                            )

                        [modelData:protected] => Array
                            (
                                [columnHeader] => Array
                                    (
                                        [dimensions] => Array
                                            (
                                                [0] => ga:hour
                                                [1] => ga:segment
                                            )

                                        [metricHeader] => Array
                                            (
                                                [metricHeaderEntries] => Array
                                                    (
                                                        [0] => Array
                                                            (
                                                                [name] => ga:pageviews
                                                                [type] => INTEGER
                                                            )

                                                    )

                                            )

                                    )

                                [data] => Google_Service_AnalyticsReporting_ReportData Object
                                    (
                                        [collection_key:protected] => totals
                                        [dataLastRefreshed] => 
                                        [isDataGolden] => 
                                        [maximumsType:protected] => Google_Service_AnalyticsReporting_DateRangeValues
                                        [maximumsDataType:protected] => array
                                        [minimumsType:protected] => Google_Service_AnalyticsReporting_DateRangeValues
                                        [minimumsDataType:protected] => array
                                        [rowCount] => 6
                                        [rowsType:protected] => Google_Service_AnalyticsReporting_ReportRow
                                        [rowsDataType:protected] => array
                                        [samplesReadCounts] => 
                                        [samplingSpaceSizes] => 
                                        [totalsType:protected] => Google_Service_AnalyticsReporting_DateRangeValues
                                        [totalsDataType:protected] => array
                                        [internal_gapi_mappings:protected] => Array
                                            (
                                            )

                                        [modelData:protected] => Array
                                            (
                                                [rows] => Array
                                                    (
                                                        [0] => Array
                                                            (
                                                                [dimensions] => Array
                                                                    (
                                                                        [0] => 00
                                                                        [1] => After Midnight
                                                                    )

                                                                [metrics] => Array
                                                                    (
                                                                        [0] => Array
                                                                            (
                                                                                [values] => Array
                                                                                    (
                                                                                        [0] => 15
                                                                                    )

                                                                            )

                                                                    )

                                                            )

                                                        [1] => Array
                                                            (
                                                                [dimensions] => Array
                                                                    (
                                                                        [0] => 01
                                                                        [1] => After Midnight
                                                                    )

                                                                [metrics] => Array
                                                                    (
                                                                        [0] => Array
                                                                            (
                                                                                [values] => Array
                                                                                    (
                                                                                        [0] => 3
                                                                                    )

                                                                            )

                                                                    )

                                                            )

                                                        [2] => Array
                                                            (
                                                                [dimensions] => Array
                                                                    (
                                                                        [0] => 15
                                                                        [1] => Before Midnight
                                                                    )

                                                                [metrics] => Array
                                                                    (
                                                                        [0] => Array
                                                                            (
                                                                                [values] => Array
                                                                                    (
                                                                                        [0] => 3
                                                                                    )

                                                                            )

                                                                    )

                                                            )

                                                        [3] => Array
                                                            (
                                                                [dimensions] => Array
                                                                    (
                                                                        [0] => 16
                                                                        [1] => Before Midnight
                                                                    )

                                                                [metrics] => Array
                                                                    (
                                                                        [0] => Array
                                                                            (
                                                                                [values] => Array
                                                                                    (
                                                                                        [0] => 7
                                                                                    )

                                                                            )

                                                                    )

                                                            )

                                                        [4] => Array
                                                            (
                                                                [dimensions] => Array
                                                                    (
                                                                        [0] => 19
                                                                        [1] => Before Midnight
                                                                    )

                                                                [metrics] => Array
                                                                    (
                                                                        [0] => Array
                                                                            (
                                                                                [values] => Array
                                                                                    (
                                                                                        [0] => 5
                                                                                    )

                                                                            )

                                                                    )

                                                            )

                                                        [5] => Array
                                                            (
                                                                [dimensions] => Array
                                                                    (
                                                                        [0] => 22
                                                                        [1] => Before Midnight
                                                                    )

                                                                [metrics] => Array
                                                                    (
                                                                        [0] => Array
                                                                            (
                                                                                [values] => Array
                                                                                    (
                                                                                        [0] => 4
                                                                                    )

                                                                            )

                                                                    )

                                                            )

                                                    )

                                                [totals] => Array
                                                    (
                                                        [0] => Google_Service_AnalyticsReporting_DateRangeValues Object
                                                            (
                                                                [collection_key:protected] => values
                                                                [pivotValueRegionsType:protected] => Google_Service_AnalyticsReporting_PivotValueRegion
                                                                [pivotValueRegionsDataType:protected] => array
                                                                [values] => Array
                                                                    (
                                                                        [0] => 37
                                                                    )

                                                                [internal_gapi_mappings:protected] => Array
                                                                    (
                                                                    )

                                                                [modelData:protected] => Array
                                                                    (
                                                                    )

                                                                [processed:protected] => Array
                                                                    (
                                                                    )

                                                            )

                                                    )

                                                [minimums] => Array
                                                    (
                                                        [0] => Array
                                                            (
                                                                [values] => Array
                                                                    (
                                                                        [0] => 3
                                                                    )

                                                            )

                                                    )

                                                [maximums] => Array
                                                    (
                                                        [0] => Array
                                                            (
                                                                [values] => Array
                                                                    (
                                                                        [0] => 15
                                                                    )

                                                            )

                                                    )

                                            )

                                        [processed:protected] => Array
                                            (
                                                [totals] => 1
                                            )

                                    )

                            )

                        [processed:protected] => Array
                            (
                                [data] => 1
                            )

                    )

            )

    )

[processed:protected] => Array
    (
        [reports] => 1
    )

)

The data I am interested in is located here: [modelData:protected] => [reports] => [0] => [modelData:protected] => [data] => [modelData:protected] => [rows] => [].

The problem is that, because the segments are applied to every day, I receive data 'before midnight' and 'after midnight' for both days. (I don't mention that the data is also sampled by hours). And there is no sign what day the values are related to.

So, the question is: Is there a possibility to find what day the data is related to?


Solution

  • I finally solved the problem. I decided to analyze live data with different requests.

    So it turns out that with one date range, like this:

    $dateRange = new Google_Service_AnalyticsReporting_DateRange();
    $dateRange->setStartDate('yesterday');
    $dateRange->setEndDate('today');
    

    the metric values are summed. That is, this metric value, which you can see below with [values] key, consists of values for 'today' and 'yesterday' of hour '19':

    [4] => Array
      (
        [dimensions] => Array
          (
            [0] => 19
            [1] => Before Midnight
          )
        [metrics] => Array
          (
            [0] => Array
              (
                [values] => Array
                  (
                    [0] => 5
                  )
               )
          )
       )
    

    But if we set two date ranges:

    $dateRange[0] = new Google_Service_AnalyticsReporting_DateRange();
    $dateRange[0]->setStartDate('yesterday');
    $dateRange[0]->setEndDate('yesterday');
    
    $dateRange[1] = new Google_Service_AnalyticsReporting_DateRange();
    $dateRange[1]->setStartDate('today');
    $dateRange[1]->setEndDate('today');
    
    $request->setDateRanges($dateRange);
    

    one for 'yesterday' and another for 'today' the metric value with [values] key will have two elements of the array, where the first one with [0] index will be related to the date range set the first and the second one with [1] index will be related to the date range set the second:

    [4] => Array
      (
        [dimensions] => Array
          (
            [0] => 19
            [1] => Before Midnight
          )
        [metrics] => Array
          (
            [0] => Array
              (
                [values] => Array
                  (
                    [0] => 2
                    [1] => 3
                  )
               )
          )
       )
    

    So we can pick all values with [0] index where [dimensions] is 'Before midnight', and all values with [1] index where [dimensions] is 'After midnight', and sum them together. And the sum will be all pages view for the time frame starting at 20:00 and ending at 03:00. Voila! Hope this my explanation will help someone looking for a solution.