简体   繁体   English

RecursiveDirectoryIterator对“打开的文件太多”抛出UnexpectedValueException

[英]RecursiveDirectoryIterator throws UnexpectedValueException on “Too many open files”

The following code: 以下代码:

$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();

Throws the following exception if there are too many files in a sub-folder which you're trying to iterate over: 如果您尝试迭代的子文件夹中有太多文件,则会引发以下异常:

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

How can you successfully iterate over a large amount of folders and files without experiencing this exception? 如何在不遇到此异常的情况下成功迭代大量文件夹和文件?

Simply by converting the iterator to an array with the iterator_to_array function, it seems like you can iterate over as many files as you'd like: 只需将迭代器转换为带有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";
  }
}

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

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