Google analytics api - get page views by URL

☆樱花仙子☆ 提交于 2019-12-24 16:34:00

问题


I was able to run de "hello" app from google analytics api:

function getFirstProfileId($analytics) {
    // Get the user's first view (profile) ID.

    // Get the list of accounts for the authorized user.
    $accounts = $analytics->management_accounts->listManagementAccounts();

    if (count($accounts->getItems()) > 0) {
        $items = $accounts->getItems();
        $firstAccountId = $items[0]->getId();

        // Get the list of properties for the authorized user.
        $properties = $analytics->management_webproperties
                ->listManagementWebproperties($firstAccountId);

        if (count($properties->getItems()) > 0) {
            $items = $properties->getItems();
            $firstPropertyId = $items[0]->getId();

            // Get the list of views (profiles) for the authorized user.
            $profiles = $analytics->management_profiles->listManagementProfiles($firstAccountId, $firstPropertyId);

            if (count($profiles->getItems()) > 0) {
                $items = $profiles->getItems();

                // Return the first view (profile) ID.
                return $items[0]->getId();

            } else {
                throw new Exception('No views (profiles) found for this user.');
            }
        } else {
            throw new Exception('No properties found for this user.');
        }
    } else {
        throw new Exception('No accounts found for this user.');
    }
}

function getResults($analytics, $profileId) {
    // Calls the Core Reporting API and queries for the number of sessions
    // for the last seven days.
    return $analytics->data_ga->get(
        'ga:' . $profileId,
        '7daysAgo',
        'today',
        'ga:sessions'
    );
}

That returns the page views for the (whole) account. But I would like to get the page views ( for the whole range ) for a specific url,

I'm trying to find how to do so, but the most similar page that I found, seems to be written in a different syntax. So I don't know how to enter those params in the current app.

Any thoughts?

--EDIT--

For more information, the previous code, prints:

But this code ( with the "syntax" of the link I provided before )

function getReport($analytics) {

  // Replace with your view ID, for example XXXX.
  $VIEW_ID = "40xxxyyy9"; // I got it from The Google Account Explorer 

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

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( $metricHeaders ) && $j < count( $metrics ); $j++) {
        $entry = $metricHeaders[$j];
        $values = $metrics[$j];
        print("Metric type: " . $entry->getType() . "\n" );
        for ( $valueIndex = 0; $valueIndex < count( $values->getValues() ); $valueIndex++ ) {
          $value = $values->getValues()[ $valueIndex ];
          print($entry->getName() . ": " . $value . "\n");
        }
      }
    }
  }
}

Prints out:

 Uncaught exception 'Google_Service_Exception' with message '{ "error": { "code": 403, "message": "Google Analytics Reporting API has not been used in project api-project-395xxxxxxx2105 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/analyticsreporting.googleapis.com/overview?project=api-project-395xxxxxxx2105 then retry.

And if I follow the console link to my project. It let me know that is already enabled ( otherwise the first code in the question shouldn't work )


回答1:


Your example actually return the number of sessions, not pageviews. So to get the number of pageviews for an Url you would need to a) change ga:sessions to ga:pageViews and b) apply a filter that limits the data to the expected Url.

Filters can by applied by passing them as part of an array of optional parameters, so you'd need to change your function a bit (this basically taken from the documentation):

function getResults($analytics, $profileId) {

    $optParams = array(
          'filters' => 'ga:pagePath=@/my/url'
    );

    return $analytics->data_ga->get(
        'ga:' . $profileId,
        '7daysAgo',
        'today',
        'ga:pageViews',
        $optParams
    );
}

IIRC =@ should be a partial match in a filter (else consult the documentation) and of course you need to change "/my/url" to your actual url.

Also note my comment about different API versions.



来源:https://stackoverflow.com/questions/46039271/google-analytics-api-get-page-views-by-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!