Search code examples
phpgoogle-analyticsgoogle-analytics-apigoogle-analytics-firebase

How to set a segment filter on Google Analytics Reporting API v4


I am trying to add a segment filter when returning data from Google Analytics Core Reporting API and have the following code:

<?php

function getReport($analytics)
{
    $VIEW_ID = "XXX";

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

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

    $goalCompletionAll = new Google_Service_AnalyticsReporting_Metric();
    $goalCompletionAll->setExpression("ga:goalCompletionsAll");
    $goalCompletionAll->setAlias("goalCompletionsAll");

    // Create first dimension object
    $dimensionChannel = new Google_Service_AnalyticsReporting_Dimension();
    $dimensionChannel->setName('ga:channelGrouping');

    // Create second dimension object
    $dimensionSource = new Google_Service_AnalyticsReporting_Dimension();
    $dimensionSource->setName('ga:source');

    // Create Segment object
    $segments = new Google_Service_AnalyticsReporting_Segment();
    $segments->setSegmentId('gaid::-4');

    // Create the ordering object
    $ordering = new Google_Service_AnalyticsReporting_OrderBy();
    $ordering->setFieldName("ga:sessions");
    $ordering->setOrderType("VALUE");
    $ordering->setSortOrder("DESCENDING");

    // Create the Report Request object
    $request = new Google_Service_AnalyticsReporting_ReportRequest();
    $request->setViewId($VIEW_ID);
    $request->setDateRanges($dateRange);

    // Set the metric
    $request->setMetrics([
            $sessions,
            $goalCompletionAll,
    ]);

    // Set the dimension
    $request->setDimensions([
        $dimensionChannel, 
        $dimensionSource
    ]);


    // Set the segments
    $request->setSegments($segments);

    // Set ordering
    $request->setOrderBys($ordering);

    $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
    $body->setReportRequests(array($request));

    return $analytics->reports->batchGet($body);
}

But when I run this code I get the following error:

Requests with segments must have ga:segment dimension.

I followed the example I found was this answer in Java (the segment Id part). I have got segment ID's setup so, what would I need to do to send in the request for ga:segement dimension?


Solution

  • You must create a segment dimension :

            $dimensionSegment= new Google_Service_AnalyticsReporting_Dimension();
            $dimensionSegment->setName("ga:segment");
    

    And add it to your request :

    $request->setDimensions([
        $dimensionChannel, 
        $dimensionSource, 
        $dimensionSegment
    ]);