phpgoogle-analyticsgoogle-reporting-api

Adding ga:pagePath dimension to get page views for a particular URL using Google Analytics Reporting API v4


The query explorer(https://ga-dev-tools.appspot.com/query-explorer/) specifies to add filter ga:pagePath with the URL as value to get the page views for a particular URL.

For the new Reporting API, I tried adding ga:pagePath as a dimension, but it returns no results. Here is the code:

  $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:pageviews");
  $sessions->setAlias("pageviews");

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

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

  // Create Dimension Filter.
  $dimensionFilter = new Google_Service_AnalyticsReporting_SegmentDimensionFilter();
  $dimensionFilter->setDimensionName("ga:pagePath");
  $dimensionFilter->setOperator("EXACT");
  $dimensionFilter->setExpressions(array("/post/digital-footprints-the-trails-you-leave-on-the-web"));

  // 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("Pageview for the URL");

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


  // Create the ReportRequest object.
  $request = new Google_Service_AnalyticsReporting_ReportRequest();
  $request->setViewId($VIEW_ID);
  $request->setDateRanges($dateRange);
  $request->setDimensions(array($path, $segmentDimensions));
  $request->setSegments(array($segment));
  $request->setMetrics(array($sessions));

  $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $body->setReportRequests( array( $request) );
  return $analytics->reports->batchGet( $body );

Any help would be appreciated. Basically I am trying to create a Cron Job, which will use the Google Analytics Reporting API to fetch pageviews for various articles on my website, and update the same in the database, this will be done, once or may be twice a day. Below is the code, I am currently using to print the report:

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++) {
        print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n");
      }

      for ($j = 0; $j < count($metrics); $j++) {
        $values = $metrics[$j]->getValues();
        for ($k = 0; $k < count($values); $k++) {
          $entry = $metricHeaders[$k];
          print($entry->getName() . ": " . $values[$k] . "\n");
        }
      }
    }
  }
}

Solution

  • I have found a solution to this problem. However, I did not choose the object-oriented approach, but rather an array to generate the query. I hope this helps you solve your problem.

    // Load the Google API PHP Client Library.

    require_once __DIR__ . '/vendor/autoload.php';
    $VIEW_ID = "replace_with_your_id";
    $start_date = "2017-01-01";
    $end_date = "2017-12-31";
    
    $analytics = initializeAnalytics();
    $reports = getReports("/f/0w3ciqnw");
    if ($reports) echo getViews($reports);
    
    
    /**
     * Initializes an Analytics Reporting API V4 service object.
     *
     * @return An authorized Analytics Reporting API V4 service object.
     */
    function initializeAnalytics()
    {
    
        // Use the developers console and download your service account
        // credentials in JSON format. Place them in this directory or
        // change the key file location if necessary.
        $KEY_FILE_LOCATION = '../service-account-credentials.json';
    
        // Create and configure a new client object.
        $client = new Google_Client();
        $client->setApplicationName("FriendChip Analytics Reporting");
        $client->setAuthConfig($KEY_FILE_LOCATION);
        $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
        $analytics = new Google_Service_AnalyticsReporting($client);
    
        return $analytics;
    }
    
    function getReports($page_path)
    {
        global $VIEW_ID, $start_date, $end_date, $analytics;
    
        $query = [
            "viewId" => $VIEW_ID,
            "dateRanges" => [
                "startDate" => $start_date,
                "endDate" => $end_date
            ],
            "metrics" => [
                "expression" => "ga:pageviews"
            ],
            "dimensions" => [
                "name" => "ga:pagepath"
            ],
            "dimensionFilterClauses" => [
                'filters' => [
                    "dimension_name" => "ga:pagepath",
                    "operator" => "ENDS_WITH", // valid operators can be found here: https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet#FilterLogicalOperator
                    "expressions" => $page_path
                ]
            ]
        ];
    
    
        // build the request and response
        $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
        $body->setReportRequests(array($query));
        // now batchGet the results https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet
        $report = $analytics->reports->batchGet($body);
        return $report;
    }
    
    function getViews($reports)
    {
        $rows = $reports[0]->getData()->getRows();
        if ($rows){
            $metrics = $rows[0]->getMetrics()[0]->values[0];
            if ($metrics){
                return $metrics;
            }
        }
        return false;
    }