Google Drive PHP Client Library Retrieve a list of

2020-07-22 16:34发布

问题:

I try to use this function in my code: https://developers.google.com/drive/v2/reference/files/list

Here below:

/**
 * Retrieve a list of File resources.
 *
 * @param apiDriveService $service Drive API service instance.
 * @return Array List of File resources.
 */
function retrieveAllFiles($service) {
  $result = array();
  $pageToken = NULL;

  do {
    try {
      $parameters = array();
      if ($pageToken) {
        $parameters['pageToken'] = $pageToken;
      }
      $files = $service->files->listFiles($parameters);

      array_merge($result, $files->getItems()); // <---- Exception is throw there !
      $pageToken = $files->getNextPageToken();
    } catch (Exception $e) {
      print "An error occurred: " . $e->getMessage();
      $pageToken = NULL;
    }
  } while ($pageToken);
  return $result;
}

But i got this error:

Fatal error: Call to a member function getItems() on a non-object in C:\Program Files (x86)\EasyPHP-5.3.6.1\www\workspace\CPS\class\controller\CtrlGoogleDrive.php on line 115

Thee array seems to be empty may be but it shouldn't be:

Array
(
    [kind] => drive#fileList
    [etag] => "WtRjAPZWbDA7_fkFjc5ojsEvE7I/lmSsH-kN3I4LpwShGKUKAM7cxbI"
    [selfLink] => https://www.googleapis.com/drive/v2/files
    [items] => Array
        (
        )

)

回答1:

The PHP client library can operate in two ways and either return objects or associative arrays, with the latter being the default.

The examples in the documentation assume you want the library to return objects, otherwise you would have to replace the following two calls:

$files->getItems()
$files->getNextPageToken()

with the corresponding calls that use associative arrays instead:

$files['items']
$files['nextPageToken']

Even better, you can configure the library to always return objects by setting

$apiConfig['use_objects'] = true;

Please check the config.php file for more configuration options:

http://code.google.com/p/google-api-php-client/source/browse/trunk/src/config.php