Home / PHP / Paging through result data from the Google Analytics API PHP Class

Paging through result data from the Google Analytics API PHP Class

I had a query the other day about paging through Google Analytics API data using my PHP Class; Google allows a maximum of 1000 records to be returned at a time per request so you need to loop until there’s no more data, requesting 1000 records at a time starting from offset 1001, 2001 etc.

Read more about my Google Analytics API PHP class and download the class and example files.

data method parameters

The ->data() method takes a number of parameters which are as follows (I may modify the class (or rewrite) at a later date to make these class properties instead of having so many parameters passed to a function call):

  • $id – the profile id to query data for
  • $dimension – the dimension(s) to retrieve data for
  • $metric – the metric(s) to retrive data for
  • $sort – the sort order for data
  • $start – the start date in YYYY-MM-DD format
  • $end – the end date inYYYY-MM-DD format
  • $max_results – the maximum number of results to return
  • $start_index – the index to start from, if $max_results is 1000 then the second “page” of data would have a start index of 1001
  • $filters – information to filter the data
  • $debug – if true will echo out the URL that is called when asking Google for data

Looping until the end of data

The following data call will get the page path and number of pageviews for all data in a specified date range (last month as of the writing of this post). It then loops through the data returned from Google until there is no more.

$data = true;
 $index = 1;
 $increment = 1000;
 while($data) {
 $data = $api->data($id, "ga:pagePath", "ga:pageviews", "", 
 "2009-05-01", "2009-05-31", $increment, $index);
 // do something with the data here
 $index += $increment;
 }

$data is set to true before the loop so it will loop at least once. You could equally do a do { } while() loop and not set $data before the loop but I’m not a fan of do … while.

$index is the index to get data from. It’s incremented at the end of each loop by the $increment amount.

$increment is the number of rows to get each time and also the offset to add to $index at the end of each loop.

When no more data comes back from the GA API while($data) will evaluate to false and the loop will end. Of course, if you have a lot of data for the selected dimension(s) and metric(s) it may take a long time for this to run. You may want to limit the number of queries instead of going for all data in this instance.