'How to list objects in Google Cloud Storage from PHP
I am trying to list objects in a folder within a Google Cloud Storage bucket. I can get a result with 1000 objects easily (or increase the number if I want) using the following code:
$names = [];
$bucket = $client->bucket('mybucketname');
$options = ['prefix' => 'myfoldername', 'fields' =>' items/name,nextPageToken'];
$objects = $bucket->objects($options);
foreach ($objects as $object) {
$names[] = $object->name();
}
So far so good, but now I want to get the next 1000 objects (or whatever limit I set using maxResults and resultLimit) using the fact that I specified the nextPageToken object. I know that I have to do this by specifying pageToken as an option - it's just that I have no idea how.
I expect my final code will look something like this - what I need is the line of code which retrieves the next page token.
$names = [];
$bucket = $client->bucket('mybucketname');
$options = ['prefix' => 'myfoldername', 'fields' =>' items/name,nextPageToken'];
while(true) {
$objects = $bucket->objects($options);
foreach ($objects as $object) {
$names[] = $object->name();
}
$nextPageToken = $objects->getNextPageTokenSomehowOrOther(); // @todo Need help here!!!!!!!
if (empty($objects) || empty($nextPageToken)){
break;
}
$options['pageToken'] = $nextPageToken;
}
Any ideas?
Solution 1:[1]
The nextPageToken is the name of the last object of the first request encoded in Base64.
Here we have an example from the documentation:
{
"kind": "storage#objects",
"nextPageToken": "CgtzaGliYS0yLmpwZw==",
"items": [
objects Resource
…
]
}
If you decode the value "CgtzaGliYS0yLmpwZw==" this will reveal the value "shiba-2.jpg"
Here we have the definition of PageToken based on API documentation:
The pageToken is an encoded field that marks the name and generation of the last object in the returned list. In a subsequent request using the pageToken, items that come after the pageToken are shown (up to maxResults).
References:
- https://cloud.google.com/storage/docs/json_api/v1/objects/list#parameters
- https://cloud.google.com/storage/docs/paginate-results#rest-paginate-results
See ya
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Eumagnun |
