php – RecursiveDirectoryIterator对“打开的文件过多”抛出UnexpectedValueException

以下代码
$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";
  }
}

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...