Google AnalyticsAPI如何检索下一页数据

时间:2015-01-27 15:50:23

标签: php google-analytics google-client

我正在使用Google AnalyticsAPI来检索我的某个配置文件的报告数据。如果报告中的行数超过1000,则响应包含1,000个结果以及名为nextPage的参数,其中包含下一页数据的URL。我很困惑如何实际使用此URL来检索数据。我使用什么API方法来实际获取下一页数据。这是我的代码:

$client = new Google_Client();
$client->setApplicationName('Google Analytics'); // name of your app

// set assertion credentials
$client->setAssertionCredentials(
  new Google_Auth_AssertionCredentials(

    GOOGLE_ANALYTICS_SERVICE_EMAIL, // email you added to GA

    array('https://www.googleapis.com/auth/analytics.readonly'),

    file_get_contents(storage_path().'/keys/privatekey.p12')  // keyfile you downloaded

));

$client->setClientId(GOOGLE_ANALYTICS_CLIENT_ID);           // from API console

$service = new Google_Service_Analytics($client);

$result = $service->data_ga->get(
        'ga:'.DEFAULT_VIEW_ID,
        '2014-09-01',
        '2015-01-26',
        'ga:uniquePageViews',
        array(
                'dimensions'=>'ga:dimension1',
                'filters'=>'ga:dimension3==product'
        )
);

print_r($result);

结果是Google_Service_Analytics_GaData对象,其中包含1000行的数据加上:

[nextLink] => https://www.googleapis.com/analytics/v3/data/ga?ids=ga:86454007&dimensions=ga:dimension1&metrics=ga:uniquePageViews&filters=ga:dimension3%3D%3Dproduct&start-date=2014-09-01&end-date=2015-01-26&start-index=1001&max-results=1000

如何使用此nextLink检索下一页数据?必须有一些内置于Google SDK中的机制,对吧?

1 个答案:

答案 0 :(得分:1)

如果您查看该链接中的参数,您会发现它与原始查询相同,但start-index值设置为1001

https://www.googleapis.com/analytics/v3/data/ga?
  ids=ga:86454007&
  dimensions=ga:dimension1&
  metrics=ga:uniquePageViews&
  filters=ga:dimension3%3D%3Dproduct&
  start-date=2014-09-01&
  end-date=2015-01-26&
  start-index=1001&
  max-results=1000

所以基本上你必须继续进行查询,直到start-index + itemsPerPage> totalResults。此外,如果您知道自己拥有大型数据集,则通常可以将max-results字段设置为更高的字段10000

它不是PHP SDK的一部分,但this module显示了在达到totalResults之前发出多个请求的示例。