Skip to content

Commit a63614a

Browse files
committed
Update pagination sample to show how to set offset
1 parent acf43d1 commit a63614a

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

google-analytics-data/src/run_report_with_pagination.php

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ function run_report_with_pagination(string $propertyId)
4747
// Create an instance of the Google Analytics Data API client library.
4848
$client = new BetaAnalyticsDataClient();
4949

50+
// [START analyticsdata_run_report_with_pagination_page1]
5051
// Make an API call.
5152
$request = (new RunReportRequest())
5253
->setProperty('properties/' . $propertyId)
@@ -68,19 +69,42 @@ function run_report_with_pagination(string $propertyId)
6869
])
6970
->setLimit(100000)
7071
->setOffset(0);
72+
73+
$requestCount = 1;
74+
printf('Sending request #%d' . PHP_EOL, $requestCount);
75+
7176
$response = $client->runReport($request);
77+
# [END analyticsdata_run_report_with_pagination_page1]
78+
79+
printRunReportResponseWithPagination($response, $requestCount);
7280

73-
printRunReportResponseWithPagination($response);
81+
// [START analyticsdata_run_report_with_pagination_page2]
82+
$rowsReceived = count($response->getRows());
83+
$totalRows = $response->getRowCount();
84+
85+
// Run the same report with an increased offset value to retrieve each additional
86+
// page until all rows are received.
87+
while ($rowsReceived < $totalRows) {
88+
$request = $request->setOffset($rowsReceived);
89+
$requestCount++;
90+
printf('Sending request #%d' . PHP_EOL, $requestCount);
91+
92+
$response = $client->runReport($request);
93+
$rowsReceived += count($response->getRows());
94+
printRunReportResponseWithPagination($response, $requestCount);
95+
}
96+
// [END analyticsdata_run_report_with_pagination_page2]
7497
}
7598

7699
/**
77100
* Print results of a runReport call.
78101
* @param RunReportResponse $response
102+
* @param int $requestCount
79103
*/
80-
function printRunReportResponseWithPagination(RunReportResponse $response)
104+
function printRunReportResponseWithPagination(RunReportResponse $response, int $requestCount)
81105
{
82106
// [START analyticsdata_print_run_report_response_header]
83-
printf('%s rows received%s', $response->getRowCount(), PHP_EOL);
107+
printf('%s rows received for request #%d%s', count($response->getRows()), $requestCount, PHP_EOL);
84108
foreach ($response->getDimensionHeaders() as $dimensionHeader) {
85109
printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL);
86110
}

0 commit comments

Comments
 (0)