php - RecursiveDirectoryIterator 在 "Too many open files"上抛出 UnexpectedValueException

标签 php iterator iteration

以下代码:

$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

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

最佳答案

只需将迭代器转换为带有 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";
  }
}

关于php - RecursiveDirectoryIterator 在 "Too many open files"上抛出 UnexpectedValueException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7153826/

相关文章:

c - 如何遍历结构数组

python - 为什么这个 OpenCV 掩蔽函数不迭代?

javascript - 当模式框关闭时,如何将我的复选框重置为未选中状态?

php - 在我的网站上禁用 cookie

java - 单链表上的双向迭代

c++ - 带有从 std::map 的迭代器到 std::list 的迭代器的 std::map

Javascript。棘手的 : Are all array values consistent?(即 : does a = [a, a,a,a])适用于任何大小的数组

javascript - JQuery 类添加/删除不起作用(使用未知的委托(delegate))

php - 防止在 Yii 框架上使用 ajaxButton/ajaxSubmitButton 加载 jQuery Assets

c++ - "Cannot convert parameter"使用 boost::variant 迭代器