【问题标题】:How can I create files and zip them without writing the files to disc?如何在不将文件写入光盘的情况下创建文件并压缩它们?
【发布时间】:2013-01-18 02:18:35
【问题描述】:

我想创建 5 个不同的文件来存储我的数据库中的数据。我想压缩 5 个文件并让这个函数返回 zip。

我可以创建这 5 个文件而不将它们实际写入磁盘吗?我从 db 得到的数据只是字符串,所以每个文件都会是一个长字符串。

我只是想这样做:

function getZippedFiles()
 // Create 1..5 files
 // Zip them up
 // Return zip
end

main()
// $zip_file = getZippedFiles();
end

非常感谢任何有关如何执行此操作的信息,谢谢!

【问题讨论】:

    标签: php zipfile createfile


    【解决方案1】:

    当然可以,使用 ZipArchive

    非常简单
    // What the array structure should look like [filename => file contents].
    $files = array('one.txt' => 'contents of one.txt', ...);
    
    // Instantiate a new zip archive.
    $zip_file = new ZipArchive;
    
    // Create a new zip. This method returns false if the creation fails.
    if(!$zip_file->open('directory/to/save.zip', ZipArchive::CREATE)) {
        die('Error creating zip!');
    }
    
    // Iterate through all of our files and add them to our zip stream.
    foreach($files as $file => $contents) {
        $zip_file->addFromString($file, $contents);
    }
    
    // Close our stream.
    $zip_file->close();
    

    【讨论】:

    • 太棒了,会拍的。谢谢。
    • 是否可以只返回 $zip_file 而不是将其保存到光盘?
    • 你打算用它做什么?
    • 我会将压缩包传递给另一个脚本,然后该脚本将解压缩并将其写入光盘。创建 zip 的脚本位于不同的服务器上,这就是为什么我想将其作为 zip 传递以使其更快。
    • 我认为这不是解决您想做的事情的最佳方式。为什么不将数据库数据发布到脚本?更好的是,如果可以的话,合并脚本?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 1970-01-01
    • 2016-12-18
    • 2022-11-21
    • 2017-08-18
    • 2021-06-03
    • 2017-10-22
    相关资源
    最近更新 更多