Yevhenii Shashkov
Yevhenii Shashkov

Reputation: 474

How to use pagination to retrieve next result set?

enter image description here

I have Google Analytics PHP API. Everything works fine. But i need to get [nextLink] => https://www.googleapis.com/analytics/v3/data/ga?ids=ga:.... data from [nextLink].
So question is how to get to the next page of data, by using [nextLink] url in result array.

I know that almost similar question was asked once but it has no answers so i asked it cuz i can't find solution.

I am very interested to see some little php code example, plus please, thanks :)

As result i see array of data:

[columnHeadersType:protected] => Google_Service_Analytics_GaDataColumnHeaders
    [columnHeadersDataType:protected] => array
    [containsSampledData] => 
    [dataTableType:protected] => Google_Service_Analytics_GaDataDataTable
    [dataTableDataType:protected] => 
    [id] => https://www.googleapis.com/analytics..........
    [itemsPerPage] => 1000
    [kind] => analytics#gaData
    [nextLink] => https://www.googleapis.com/analytics/v3/data........&start-index=1001&max-results=1000
    [previousLink] => 
    [profileInfoType:protected] => Google_Service_Analytics_GaDataProfileInfo
    [profileInfoDataType:protected] => 
    [queryType:protected] => Google_Service_Analytics_GaDataQuery
    [queryDataType:protected] => 
    [rows] => Array

Main php code is:

function getService()
{
  // Creates and returns the Analytics service object.

  // Load the Google API PHP Client Library.
require_once LOCATION.'/google/vendor/autoload.php';


  // Use the developers console and replace the values with your
  // service account email, and relative location of your key file.
  $service_account_email = '[email protected]';
  $key_file_location = LOCATION.'/xxxx.p12';

  // Create and configure a new client object.
  $client = new Google_Client();
  $client->setApplicationName("HelloAnalytics");
  $analytics = new Google_Service_Analytics($client);

  // Read the generated client_secrets.p12 key.
  $key = file_get_contents($key_file_location);
  $cred = new Google_Auth_AssertionCredentials(
      $service_account_email,
      array(Google_Service_Analytics::ANALYTICS_READONLY),
      $key
  );
  $client->setAssertionCredentials($cred);
  if($client->getAuth()->isAccessTokenExpired()) {
    $client->getAuth()->refreshTokenWithAssertion($cred);
  }

  return $analytics;
}

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) {

      $params = array('dimensions' => 'ga:pagePath,ga:deviceCategory,ga:city,ga:operatingSystem,ga:screenResolution,ga:sourceMedium,ga:keyword');
     return $analytics->data_ga->get(
       'ga:' . $profileId,
       'yesterday',
       'yesterday',
       'ga:sessions,ga:hits,ga:sessionDuration',$params);
}

function printResults(&$results) {
  // Parses the response from the Core Reporting API and prints
  // the profile name and total sessions.
  if (count($results->getRows()) > 0) {

    // Get the profile name.
    $profileName = $results->getProfileInfo()->getProfileName();

    // Get the entry for the first entry in the first row.
    $rows = $results->getRows();


    echo '<pre>';
    print_r($rows);


  } else {
    print "No results found.\n";
  }
}

$analytics = getService();
$profile = getFirstProfileId($analytics);
$results = getResults($analytics, $profile);
echo '<pre>';
print_r($results);
echo '<br>';

Upvotes: 3

Views: 1325

Answers (1)

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 117156

It should be something along these lines. Pagination

$token = $results->getNextPageToken();
while($token != null) {


    $params = array('dimensions' => 'ga:pagePath,ga:deviceCategory,ga:city,ga:operatingSystem,ga:screenResolution        ,ga:sourceMedium,ga:keyword',
                'pageToken' => $token);

    $result = $analytics->data_ga->get('ga:' . $profileId,
                                   'yesterday',
                                   'yesterday',
                                   'ga:sessions,ga:hits,ga:sessionDuration',                                       $params);
   $token = $results->getNextPageToken();

}

Sorry I don't have the power of php this minute so I cant test it. But it should be close. You just need to check if there is a next link from the first request if their is I normally just loop it until I have everything.

Tip: Remember you are going to be counting 1 against your quota every time you fetch a next link.

Upvotes: 1

Related Questions