douji8017 2011-08-22 21:28
浏览 99
已采纳

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

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.
";
  } catch (Exception $e) {
    echo "ERROR: Could not add the file '$key': $e
";
  }
}

$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?

  • 写回答

1条回答 默认 最新

  • dongya9904 2011-08-22 21:31
    关注

    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 = 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.
    ";
      } catch (Exception $e) {
        echo "ERROR: Could not add the file '$key': $e
    ";
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真