【问题标题】:PHP Create Multiple CSV Files in Memory then CompressPHP 在内存中创建多个 CSV 文件然后压缩
【发布时间】:2014-12-30 14:54:52
【问题描述】:

我需要在单个 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 文件。

我怎样才能做到这一点?

【问题讨论】:

    标签: php csv


    【解决方案1】:

    试试这个...

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

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

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

    MetaShock Reference

    【讨论】:

    • 非常有帮助。非常感谢。
    【解决方案2】:

    你可以使用php的memory wrapper:

    $zipname = 'php://memory';
    

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

    【讨论】:

    • 这会支持多个文件吗?例如...$zipname1 = 'php://memory';$zipname2 = 'php://memory'; $zipname3 = 'php://memory';
    • 每个fopen('php://memory', $mode) 将在内存文件中单独打开。问题是它们没有命名,关闭文件指针会丢失写入的内容。我不知道ZipArchive 库知道这是否是一个问题,可能你不应该调用$zip-&gt;close() 而是通过其他方式来获取流。还有另一种解决方案,我会更新我的答案。
    猜你喜欢
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 2016-10-21
    • 2019-11-09
    • 1970-01-01
    相关资源
    最近更新 更多