Php zip存档是空的 [英] Php zip archive is empty

查看:102
本文介绍了Php zip存档是空的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我尝试将标记为正确的解决方案,但它没用。下载了一个zip文件,但它是空的。



我尝试过:



I need a little help here. I intended to create 2 csv files in PHP and have the browser download them. This will happen when users click a button. However, I discovered that only 1 file download is permitted for each http request. I stumbled upon this stackoverflow post. The solution creates 3 csv files in-memory and added them into a zip file and download it to the client's browser.

I tried the solution marked as correct, but it didn't work. A zip file was downloaded, but it is empty.

What I have tried:

// some data to be used in the csv files
$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
// you could also use the temp file method above for this.
unlink($zipname);

推荐答案

headers = array('id','name','age', 'species');
headers = array('id', 'name', 'age', 'species');


records = array(
array('1','gise','4','cat'),
array(' 2','hek2mgl','36','人')
);

//创建你的zip文件
records = array( array('1', 'gise', '4', 'cat'), array('2', 'hek2mgl', '36', 'human') ); // create your zip file


zipname ='file.zip';
zipname = 'file.zip';


这篇关于Php zip存档是空的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆