简体   繁体   中英

Google Analytics - Getting page view information for a URL

(Using Reporting API V4) Whenever I am trying to get the page view information via google analytics, it doesn't seem to be filtering correctly. For example with the setOperator("BEGINS_WITH"); and then setExpressions("/report"); lines, what I would expect is to only retreive pages that start with mywebsitename.com/report however it gives me all sorts of stuff such as pages that start with /tag and /sponsor in addition to a bunch(but I don't think all, not actually sure about that) of the pages starting with /report.

This continues to be an issue when dealing with more specific URLs and also when using different operators. It always returns what I'm looking for but also a bunch of other random junk that seems unrelated. I also tried using just regex, but that still gave similar stuff.

I feel like my problem likely lies in not understanding exactly what all of the various objects do (in php specifically), but I have been unable to find an answer for some of that.

The closest answer I was able to find on SO here is this however I'm not sure what I'm doing differently than this guy. I mean one thing is that I'm not using the JSON string natively, however in the documentation from google they use this weird function syntax Im using. Other than that it should be pretty much the same I think.

This is mostly a combination of example code from here and here .

<?php

// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';


$analytics = initializeAnalytics();
//print_r($analytics);
$response = getReport($analytics);
//print_r($response);
printResults($response);


/**
 * 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 = __DIR__ . '/service-account-credentials.json';

  // Create and configure a new client object.
  $client = new Google_Client();
  $client->setApplicationName("Hello Analytics Reporting");
  $client->setAuthConfig($KEY_FILE_LOCATION);
  $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
  $analytics = new Google_Service_AnalyticsReporting($client);

  return $analytics;
}


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

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

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

  //Create the dimensions dimension.
  $dimensions = new Google_Service_AnalyticsReporting_Dimension();
  $dimensions->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("BEGINS_WITH");
  $dimensionFilter->setExpressions("/report");

  // 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("Sessions with path");

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

  $request = new Google_Service_AnalyticsReporting_ReportRequest();
  $request->setViewId($VIEW_ID);
  $request->setDateRanges(array($dateRange));
  $request->setDimensions(array($dimensions, $segmentDimensions));
  $request->setSegments(array($segment));
  $request->setMetrics(array($metricss));

  // Create the GetReportsRequest object.
  $getReport = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $getReport->setReportRequests(array($request));

  // Call the batchGet method.
  $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $body->setReportRequests( array( $request) );
  $response = $analytics->reports->batchGet( $body );

  return $response;
}


/**
 * Parses and prints the Analytics Reporting API V4 response.
 *
 * @param An Analytics Reporting API V4 response.
 */
function printResults($reports) {
 // print_r("reports/n");
  //print_r($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");
        }
      }
    }
  }
}

This should be just returning the view count for the specific page path.

You can avoid the detailed code from the examples by just using the Google_Service_AnalyticsReporting_DimensionFilter and the Google_Service_AnalyticsReporting_DimensionFilterClause

So an example is this

...

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

// Create the DimensionFilter.
$dimensionFilter = new Google_Service_AnalyticsReporting_DimensionFilter();
$dimensionFilter->setDimensionName('ga:pagePath');
$dimensionFilter->setOperator('BEGINS_WITH');
$dimensionFilter->setExpressions(array('/report'));

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

...

$request->setDimensions(array($dimension));
$request->setDimensionFilterClauses(array($dimensionFilterClause));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM