在下载 php 时将文件添加到包含内容的 zip 文件中


Add file to a zip file with content while it is downloading php

我想将文件.txt添加到带有图像的zip文件中。
下载zip时,我想在不影响原始文件的情况下.txt添加文件。

那么,有可能这样做吗?还是唯一的方法是将 zip 文件解压缩到临时文件夹,然后添加 txt 文件并将其删除?

我尝试使用 tmpfile,但它只是创建一个临时文件

你可以做这样的事情:

$files = array(
    'file1',
    'file2'
);
$tmp_file = tmpfile();
$zip->open($tmp_file, ZipArchive::CREATE);
# loop through each file
foreach($files as $file){
    # download file
    $download_file = file_get_contents($file);
    #add it to the zip
    $zip->addFromString(basename($file),$download_file);
}
# close zip
$zip->close();
# send the file to the browser as a download
header('Content-disposition: attachment; filename=new-zipfile.zip');
header('Content-type: application/zip');
readfile($tmp_file);