繁体   English   中英

PHP Zip存档为空

[英]PHP Zip Archive is Empty

我需要一点帮助。 我打算在PHP中创建2个csv文件,并让浏览器下载它们。 当用户单击一个按钮时,就会发生这种情况。 但是,我发现每个http请求只允许下载1个文件。 我偶然发现了这个stackoverflow帖子, PHP在内存中创建了多个CSV文件,然后进行了压缩 该解决方案在内存中创建了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);

我尝试了标记为正确的解决方案,但没有成功。 已下载一个zip文件,但该文件为空。

var_dump($ zip)显示有3个文件。

任何帮助,将不胜感激。

PS:对不起,英语不好,我不是母语人士。

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

chmod -R 666 your_folder

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM