2011-08-22 25 views
7

下面的代碼: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 

如何成功迭代大量文件夾和文件而不會遇到此異常?

回答

7

簡單的迭代器轉換爲與iterator_to_array功能的陣列,好像你可以遍歷儘可能多的文件,如你想: