我正在尝试列出我的 Amazon S3 存储桶中的所有项目。 我其中有几个嵌套目录。
- 目录1/
- 目录1/子目录1/
- 目录1/子目录2/
- 目录1/子目录3/
- 目录2/
- 目录2/子目录1/
- 目录2/子目录2/
- ...
每个子目录包含多个文件。 我需要获取具有此文件结构的嵌套数组。
我正在使用适用于 PHP 2.4.2 的 Amazon AWS 开发工具包
这是我的代码:
$dir = 's3://bucketname';
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach ($iterator as $file) {
echo $file->getType() . ': ' . $file . "\n";
}
但是,结果仅列出位于存储桶中的文件,而不列出位于目录/子目录(带前缀的文件)或目录本身中的文件。
如果我迭代 ($dir.'/folder')
则根本没有结果。
我将 RecursiveIteratorIterator::SELF_FIRST
作为第二个参数传递给迭代器的构造函数,我仅获得第一级目录 - 没有子目录。
如何使用 AWS 流包装器和 PHP RecursiveIterator 列出我的存储桶中所有目录中的所有文件?
希望有人能帮助我。
谢谢!
最佳答案
我遇到了同样的问题,我使用以下方法解决了这个问题:
use \Aws\S3\StreamWrapper;
use \Aws\S3\S3Client;
private $files = array();
private $s3path = 'YOUR_BUCKET';
private $s3key = 'YOUR_KEY';
private $s3auth = 'YOUR_AUTH_CODE';
public function recursive($path)
{
$dirHandle = scandir($path);
foreach($dirHandle as $file)
{
if(is_dir($path.$file."/") && $file != '.' && $file != '..')
{
$this->recursive($path.$file."/");
}
else
{
$this->files[$path.$file] = $path.$file;
}
}
}
public function registerS3()
{
$client = S3Client::factory(array(
'key' => $this->s3key,
'secret' => $this->s3auth
));
$wp = new StreamWrapper();
$wp->register($client);
}
public function run()
{
$folder = 's3://'.$this->s3path.'/';
$this->registerS3();
$this->recursive($folder);
}
现在,如果您在 $this->files 中执行 DUMP,应该会显示存储桶中的所有文件。
关于php - 使用流包装器迭代 S3 存储桶,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18171518/