简体   繁体   English

PHP Zip存档为空

[英]PHP Zip Archive is Empty

I need a little help here. 我需要一点帮助。 I intended to create 2 csv files in PHP and have the browser download them. 我打算在PHP中创建2个csv文件,并让浏览器下载它们。 This will happen when users click a button. 当用户单击一个按钮时,就会发生这种情况。 However, I discovered that only 1 file download is permitted for each http request. 但是,我发现每个http请求只允许下载1个文件。 I stumbled upon this stackoverflow post PHP Create Multiple CSV Files in Memory then Compress . 我偶然发现了这个stackoverflow帖子, PHP在内存中创建了多个CSV文件,然后进行了压缩 The solution creates 3 csv files in-memory and added them into a zip file and download it to the client's browser. 该解决方案在内存中创建了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);

I tried the solution marked as correct, but it didn't work. 我尝试了标记为正确的解决方案,但没有成功。 A zip file was downloaded, but it is empty. 已下载一个zip文件,但该文件为空。

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

Any help would be appreciated. 任何帮助,将不胜感激。

PS : Sorry, bad english, I'm not a native speaker. PS:对不起,英语不好,我不是母语人士。

Your code is correct. 您的代码是正确的。 But i also had problems creating the zip-file because of permissions. 但是由于权限问题,我在创建zip文件时也遇到了问题。 You need to set right permission of the folder your script is running in and also of the script itself. 您需要为运行脚本的文件夹以及脚本本身设置正确的权限。 Assuming you are under linux use chmod recursivly ( -R ): 假设您在Linux下,递归使用chmod-R ):

chmod -R 666 your_folder

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

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