【问题标题】:PHP output to file for download without creating file on the serverPHP 输出到文件以供下载,而无需在服务器上创建文件
【发布时间】:2013-05-11 17:52:31
【问题描述】:

我想将我的数据输出到一个文件供用户下载,而无需在服务器上实际创建该文件。文件的数据只是数组,我将其转换为 CSV 格式供用户下载。这是我的代码:

$fh = fopen('file.csv','w');
fputcsv($fh,$arr); // $arr is my array that contains the data to be parsed into CSV
fclose($out);

以上代码成功创建文件...但我不想创建文件。我想简单地流式传输输出。

任何帮助将不胜感激!

【问题讨论】:

    标签: php arrays fopen output


    【解决方案1】:

    你可以使用

    header("Content-type: text/csv");
    header("Cache-Control: no-store, no-cache");
    header('Content-Disposition: attachment; filename="content.csv"');
    ...
    $file = fopen('php://output','w');
    

    【讨论】:

    • 只需添加这些标题并打开php://output而不是文件。
    • 但有一件事:当我写入服务器时,CSV 文件看起来不错。当我输出下载时,CSV文件基本上只是网页的来源。我猜它会在屏幕上输出所有内容,而不仅仅是数组(根据我上面的代码)。有什么想法吗?
    • 是的,您必须逐行遍历阵列上的 foreachfputcsv()。如果这没有意义,请告诉我,我将添加另一个示例。
    • 我刚刚输出到一个下载文件的新窗口,它工作正常。感谢您的帮助!
    【解决方案2】:
    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename=file.csv");
    header("Pragma: no-cache");
    header("Expires: 0");
    
    echo "record1,record2,record3\n";
    

    等 小 function 被我用来选择性地编码 CSV 字段::

    function maybeEncodeCSVField($string) {
        if(strpos($string, ',') !== false || strpos($string, '"') !== false || strpos($string, "\n") !== false) {
            $string = '"' . str_replace('"', '""', $string) . '"';
        }
        return $string;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 2011-12-05
      • 2018-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多