PHP压缩文件为空

PHP压缩文件为空,php,file,csv,zip,ziparchive,Php,File,Csv,Zip,Ziparchive,我需要一点帮助。 我打算用PHP创建2个csv文件,并让浏览器下载它们。 当用户单击按钮时会发生这种情况。但是,我发现每个http请求只允许下载一个文件。我偶然发现了这根柱子。该解决方案在内存中创建3个csv文件,并将其添加到zip文件中,然后将其下载到客户端的浏览器中 $headers = array('id', 'name', 'age', 'species'); $records = array( array('1', 'gise', '4', 'cat'), array(

我需要一点帮助。 我打算用PHP创建2个csv文件,并让浏览器下载它们。 当用户单击按钮时会发生这种情况。但是,我发现每个http请求只允许下载一个文件。我偶然发现了这根柱子。该解决方案在内存中创建3个csv文件,并将其添加到zip文件中,然后将其下载到客户端的浏览器中

$headers = array('id', 'name', 'age', 'species');
$records = array(
    array('1', 'gise', '4', 'cat'),
    array('2', 'hek2mgl', '36', 'human')
);

// create your zip file
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);

// loop to create 3 csv files
for ($i = 0; $i < 3; $i++) {

    // create a temporary file
    $fd = fopen('php://temp/maxmemory:1048576', 'w');
    if (false === $fd) {
        die('Failed to create temporary file');
    }

    // write the data to csv
    fputcsv($fd, $headers);
    foreach($records as $record) {
        fputcsv($fd, $record);
    }

    // return to the start of the stream
    rewind($fd);

    // add the in-memory file to the archive, giving a name
    $zip->addFromString('file-'.$i.'.csv', stream_get_contents($fd) );
    //close the file
    fclose($fd);
}
// close the archive
$zip->close();

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);

// remove the zip archive
unlink($zipname);
$headers=数组('id','name','age','species');
$records=数组(
数组('1','gise','4','cat'),
数组('2','hek2mgl','36','human')
);
//创建您的zip文件
$zipname='file.zip';
$zip=新的ZipArchive;
$zip->open($zipname,ZipArchive::CREATE);
//循环以创建3个csv文件
对于($i=0;$i<3;$i++){
//创建一个临时文件
$fd=fopen($fd)php://temp/maxmemory:1048576","w",;
如果(false==$fd){
die('未能创建临时文件');
}
//将数据写入csv
fputcsv($fd,$headers);
foreach($记录为$记录){
fputcsv($fd,$record);
}
//返回到流的开头
倒带($fd);
//将内存中的文件添加到存档中,并给出名称
$zip->addFromString('file-'.$i..csv',stream_get_contents($fd));
//关闭文件
现金流量表(美元);
}
//关闭档案
$zip->close();
标题(“内容类型:应用程序/zip”);
标题('Content-disposition:attachment;filename='。$zipname);
标题('Content-Length:'.filesize($zipname));
readfile($zipname);
//删除压缩文件
取消链接($zipname);
我尝试了标记为正确的解决方案,但无效。 已下载zip文件,但该文件为空

任何帮助都将不胜感激


抱歉,英语不好,我不是以英语为母语的人。

您的代码是正确的。但是由于权限问题,我在创建zip文件时也遇到了问题。您需要设置脚本运行所在文件夹以及脚本本身的正确权限。假设您在linux下,递归地使用
chmod
-R
):


请提供代码中重要/失败的部分。我已通过添加代码编辑了文章。对不起,没错!!!!!!!!这确实是一个需要许可的问题。这个问题现在已经解决了。谢谢你,伙计。
chmod -R 666 your_folder