【问题标题】:Create a ZIP file containing file generated on the fly创建一个包含动态生成的文件的 ZIP 文件
【发布时间】:2017-06-22 13:18:33
【问题描述】:

我正在开发一个网络应用程序,它会提出一系列问题,然后根据这些问题生成一个文本文档。创建文档并在客户端浏览器上自动触发下载。效果很好。

但是,我现在想做的是在动态创建此文件时从该文件创建一个 ZIP 文件,并添加一些其他文件。虽然我不知道这是否可以通过 PHP 实现?

谁能给点建议?我环顾四周,但所有示例/教程都演示了从文件系统中已经存在的文件创建 ZIP 文件?

谢谢。

【问题讨论】:

标签: php zip dynamically-generated


【解决方案1】:

所以对于那些感兴趣的人,我使用了上面提到的 SO 帖子中的以下代码:

// Prepare File
$file = tempnam("tmp", "zip");
$zip = new ZipArchive();
$zip->open($file, ZipArchive::OVERWRITE);

// Stuff with content
$zip->addFromString('file_name_within_archive.ext', $your_string_data);
$zip->addFile('file_on_server.ext', 'second_file_name_within_archive.ext');

// Close and send to users
$zip->close();
header('Content-Type: application/zip');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="file.zip"');
readfile($file);
unlink($file); 

根据我的要求进行了相应调整,它可以工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2011-08-12
    • 2017-02-07
    • 1970-01-01
    • 2013-10-10
    相关资源
    最近更新 更多