【问题标题】:RecursiveDirectoryIterator throws UnexpectedValueException on "Too many open files"RecursiveDirectoryIterator 在“打开的文件太多”上抛出 UnexpectedValueException
【发布时间】:2011-11-01 12:02:00
【问题描述】:

以下代码:

$zip = new ZipArchive();

if ($zip->open('./archive.zip', ZIPARCHIVE::CREATE) !== TRUE) {
    die ("Could not open archive");
}

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("./folder/"));

foreach ($iterator as $key => $value) {
  try {
    $zip->addFile(realpath($key), $key);
    echo "'$key' successfully added.\n";
  } catch (Exception $e) {
    echo "ERROR: Could not add the file '$key': $e\n";
  }
}

$zip->close();

如果您尝试迭代的子文件夹中有太多文件,则会引发以下异常:

Uncaught exception 'UnexpectedValueException' with message 'RecursiveDirectoryIterator::__construct(./some/path/): failed to open dir: Too many open files' in /some/other/path/zip.php:24
Stack trace:
#0 [internal function]: RecursiveDirectoryIterator->__construct('./some/path/')
#1 /some/other/path/zip.php(24): RecursiveDirectoryIterator->getChildren()
#2 {main}
thrown in /some/other/path/zip.php on line 24

如何在不遇到此异常的情况下成功迭代大量文件夹和文件?

【问题讨论】:

    标签: php iterator iteration


    【解决方案1】:

    只需使用 iterator_to_array 函数将迭代器转换为数组,您就可以遍历任意数量的文件:

    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("./folder/"));
    $files = iterator_to_array($iterator, true);
    
    // iterate over the directory
    // add each file found to the archive
    foreach ($files as $key => $value) {
      try {
        $zip->addFile(realpath($key), $key);
        echo "'$key' successfully added.\n";
      } catch (Exception $e) {
        echo "ERROR: Could not add the file '$key': $e\n";
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-17
      • 2020-09-21
      • 2012-11-03
      • 1970-01-01
      • 2013-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多