PHP 在内存中创建多个 CSV 文件,然后压缩



我需要在单个 HTTP 请求期间创建 3 个 CSV 文件(在内存中),将文件压缩为单个压缩文件,并将压缩文件作为 HTTP 响应返回。

我有以下代码来创建zip文件...

$files = array($file1, $file2);
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
    $zip->addFile($file);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);

但是,我不知道如何在内存中创建CSV文件。

我怎样才能做到这一点?

试试这个...

// 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);

我刚刚在我的机器上测试了这个,它工作正常。

我用这个链接作为参考,它可能有用。

元冲击参考

你可以使用 php 的内存包装器:

$zipname = 'php://memory';

在具有文件系统/dev/shm系统上,您可以在那里创建文件,它们将仅保存在内存中,并且只能由当前进程访问。发送后不要忘记删除它们,Web 服务器进程将继续运行。

最新更新