简体   繁体   English

使用流包装器在S3存储桶中进行迭代

[英]iterating through S3 bucket with stream wrapper

I am trying to list all the items in my Amazon S3 bucket. 我正在尝试列出Amazon S3存储桶中的所有项目。 I have several nested directories in it. 我有几个嵌套的目录。

  • dir1/ DIR1 /
  • dir1/subdir1/ DIR1 / subdir1 /
  • dir1/subdir2/ DIR1 / subdir2 /
  • dir1/subdir3/ DIR1 / subdir3 /
  • dir2/ DIR2 /
  • dir2/subdir1/ DIR2 / subdir1 /
  • dir2/subdir2/ DIR2 / subdir2 /
  • ... ...

Each subdirectory contains several files. 每个子目录包含几个文件。 I need to get a nested array with this file structure. 我需要使用此文件结构获取嵌套数组。

I'm using the Amazon AWS SDK for PHP 2.4.2 我正在使用适用于PHP 2.4.2的Amazon AWS开发工具包

This is my code: 这是我的代码:

$dir = 's3://bucketname';

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));

foreach ($iterator as $file) {
    echo $file->getType() . ': ' . $file . "\n";
}

However, the result only lists files lying in the bucket, not files lying in directories/subdirectories (files with prefixes) or the directories itself. 但是,结果仅列出存储桶中的文件,而不列出目录/子目录中的文件(带前缀的文件)或目录本身。

If I iterate through ($dir.'/folder') there is no result at all. 如果我遍历($dir.'/folder')根本没有结果。

II pass RecursiveIteratorIterator::SELF_FIRST as the second argument to the constructor of the iterator, I get only first level directories – no subdirectories. 我将RecursiveIteratorIterator::SELF_FIRST作为迭代器的构造函数的第二个参数传递,我仅获得第一级目录,而没有子目录。

How can I use the AWS stream wrapper and the PHP RecursiveIterator to list all the files in all the directories in my bucket? 如何使用AWS流包装器和PHP RecursiveIterator列出存储桶中所有目录中的所有文件?

I hope someone can help me. 我希望有一个人可以帮助我。

Thank you! 谢谢!

I had the same problem, and I solved this using: 我有同样的问题,我使用以下方法解决了这个问题:

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);
}

Now, if you do a DUMP in $this->files, should show all the files on the bucket. 现在,如果您在$ this-> files中执行DUMP,则应显示存储桶中的所有文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM