dqy1265 2015-03-30 08:42
浏览 214
已采纳

我的PHP zip函数使用了太多内存

I am trying to use the function below to zip up a file that is 551 mb, but there is not memory for it to run. I have used it to zip up other file and it works fine so I think it has to do with the size of the file.

    function Zip($source, $destination)
{
    global $latest_filename;
    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }

    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE)) {
        return false;
    }

    $source = str_replace('\\', '/', realpath($source));

    if (is_dir($source) === true) {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

        foreach ($files as $file) {
            $file = str_replace('\\', '/', realpath($file));

            if (is_dir($file) === true) {
                $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
            } else if (is_file($file) === true) {
                $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }
        }
    } else if (is_file($source) === true) {
        $zip->addFromString(basename($source), file_get_contents($source));
    }

    return $zip->close();
}

Here is the error I recieve:

Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to  allocate 577311064 bytes)

Thanks for any help with this.

  • 写回答

4条回答 默认 最新

  • doushi1964 2015-04-01 08:16
    关注

    Thank you for all of your reponses to this question , What I decided to do was to create a new zipping function that did not use 'file_get_contents' as this was using up all of the memory.

    Here is my new function

    function zip2 ($zipname){
    
        $zip = new ZipArchive();
    
        $zip->open("" .$zipname. ".zip", ZipArchive::CREATE);
    
        $files = scandir("" .$zipname. "");
        unset($files[0], $files[1]);
    
        foreach ($files as $file){
            $zip->addFile("" .$zipname. "/{$file}");
        }
        $zip->close();
    }
    

    Thanks

    Colin

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错