在不超过内存的情况下压缩PHP文件


Zipping files in PHP without exceeding memory

我要做的是遍历链接列表并将它们全部压缩到同一目录中。这些文件包括图像、pdf、音频和视频。问题是,有些文件很大,我得到以下错误:

    FatalErrorException: Error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 46512453 bytes)...

这是我现在的情况:

    $zip = new ZipArchive();
    $tmp_file = tempnam('.','');
    $zip->open($tmp_file, ZipArchive::CREATE);
    foreach($mediaFiles as $file){
        $downloadFile = file_get_contents($file);
        $zip->addFromString(basename($file), $downloadFile);
    }
    $zip->close();
    header('Content-disposition: attachment; filename=download.zip');
    header('Content-type: application/zip');
    readfile($tmp_file);

检查此库,它允许创建zip文件并将其作为流返回:

http://www.phpclasses.org/package/6110-PHP-Create-archives-of-compressed-files-in-ZIP-format.html