Google analytics api - 通过网址获取网页浏览量 [英] Google analytics api - get page views by URL

查看:156
本文介绍了Google analytics api - 通过网址获取网页浏览量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  function getFirstProfileId($ analytics){
//获取用户的第一个视图(配置文件)ID。

//获取授权用户的帐户列表。
$ accounts = $ analytics-> management_accounts-> listManagementAccounts();
$ b $ if(count($ accounts-> getItems())> 0){
$ items = $ accounts-> getItems();
$ firstAccountId = $ items [0] - > getId();

//获取授权用户的属性列表。
$ properties = $ analytics-> management_webproperties
- > listManagementWebproperties($ firstAccountId);
$ b $ if(count($ properties-> getItems())> 0){
$ items = $ properties-> getItems();
$ firstPropertyId = $ items [0] - > getId();

//获取授权用户的视图列表(配置文件)。
$ profiles = $ analytics-> management_profiles-> listManagementProfiles($ firstAccountId,$ firstPropertyId); $(

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

//返回第一个视图(配置文件)ID。
return $ items [0] - > getId();

} else {
抛出新的异常('找不到此用户的视图(配置文件)'。
}
} else {
抛出新的异常('没有找到该用户的属性。');
}
} else {
抛出新的异常('没有为这个用户找到帐户');
}
}

函数getResults($ analytics,$ profileId){
//调用Core Reporting API并查询会话数
//最近七天
return $ analytics-> data_ga-> get(
'ga:'。$ profileId,
'7daysAgo',
'今天',
'ga :会议'
);
}

返回(整个)帐户的页面浏览量。 我希望获得整个范围内的网页浏览量针对特定网址



我试图找到如何去做,但最重要的是我发现的类似页面似乎是用不同的语法编写的。所以我不知道如何在当前应用程序中输入这些参数。

有什么想法?

- -EDIT -



有关更多信息,请参阅前面的代码:

但此代码我之前提供的链接的语法)

pre $函数getReport($ analytics){

/ /用您的视图ID替换,例如XXXX。
$ VIEW_ID =40xxxyyy9; //我从Google帐户资源管理器获得它

//创建DateRange对象。
$ dateRange = new Google_Service_AnalyticsReporting_DateRange();
$ dateRange-> setStartDate(7daysAgo);
$ dateRange-> setEndDate(today);

//创建Metrics对象。
$ sessions = new Google_Service_AnalyticsReporting_Metric();
$ sessions-> setExpression(ga:sessions);
$ sessions-> setAlias(sessions);

//创建ReportRequest对象。
$ 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));
返回$ analytics-> reports-> batchGet($ body); ($ reportIndex = 0; $ reportIndex< count($ reports); $ reportIndex ++){
$($ reports){



} report = $ reports [$ reportIndex];
$ header = $ report-> getColumnHeader();
$ dimensionHeaders = $ header-> getDimensions();
$ metricHeaders = $ header-> getMetricHeader() - > getMetricHeaderEntries();
$ rows = $ report-> getData() - > getRows(); ($ rowIndex = 0; $ rowIndex< count($ rows); $ rowIndex ++){
$ row = $ rows [$ rowIndex];

;
$ dimensions = $ row-> getDimensions();
$ metrics = $ row-> getMetrics(); ($ i = 0; $ i< count($ dimensionHeaders)&& $ i< count($ dimensions); $ i ++){
print($ dimensionHeaders [$ i] 。:。$ dimensions [$ i]。\\\
); ($ j = 0; $ j< count($ metricHeaders)&& $ j< count($ metrics); $ j ++){$ b $


$ b b $ entry = $ metricHeaders [$ j];
$ values = $ metrics [$ j];
print(Metric type:。$ entry-> getType()。\\\
); ($ valueIndex = 0; $ valueIndex< count($ values-> getValues()); $ valueIndex ++){
$ value = $ values-> getValues()[$ valueIndex] ;
print($ entry-> getName()。:。$ value。\\\
);
}
}
}
}
}

打印出来:

 带有消息'{error的未捕获异常'Google_Service_Exception':{code:403 ,message:Google Analytics Reporting API尚未在项目api-project-395xxxxxxx2105中使用过,或者被禁用。请访问https://console.developers.google.com/apis/api/analyticsreporting.googleapis启用它。 .com / overview?project = api-project-395xxxxxxx2105然后重试。

如果我按照控制台链接到我的项目,它让我知道已经启用(否则问题中的第一个代码应该不起作用)

解决方案

您的示例实际上返回的是会话数量,而不是综合浏览量。因此,要获取Url的综合浏览量,您需要a)将ga:sessions更改为ga:pageViews,并b)应用将数据限制为预期值的过滤器Url。



过滤器c通过将它们作为可选参数数组的一部分传递来应用,因此您需要稍微更改一下函数(基本上来自文档):

  function getResults($ analytics,$ profileId){

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

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



IIRC = @ 应该是一个过滤器中的部分匹配(或者查阅文档),当然你需要将/ my / url更改为你的实际url。



有关不同API版本的评论。


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 )

解决方案

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.

这篇关于Google analytics api - 通过网址获取网页浏览量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆