I'm using the Google Analytics API to retrieve reporting data for one of my profiles. If the number of rows in the report exceeds 1000, the response contains 1,000 results plus a parameter called nextPage
, which contains a URL for the next page of data. I am confused how to actually use this URL in order to retrieve the data. What API method to I use to actually get the next page of data. Here's my code:
$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);
The result of this is Google_Service_Analytics_GaData
object, which contains data for 1000 rows plus this:
[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
How can I use this nextLink
to retrieve the next page of data? There must be some mechanism for this built into the Google SDK, right?
If you look at the parameters in that link you'll notice it's the same as your original query, but the
start-index
value is set to1001
:So basically you have to keep doing queries until
start-index
+itemsPerPage
>totalResults
. Also, if you know you're going to have a large dataset, you can often set themax-results
field to something higher like10000
.It's not part of the PHP SDK, but this module shows an example of making multiple requests until
totalResults
is reached.