2

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

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

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

任何帮助将不胜感激!

4

2 回答 2

13

您可以使用

header("Content-type: text/csv");
header("Cache-Control: no-store, no-cache");
header('Content-Disposition: attachment; filename="content.csv"');
...
$file = fopen('php://output','w');
于 2013-05-16T17:52:45.903 回答
3
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

echo "record1,record2,record3\n";

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

function maybeEncodeCSVField($string) {
    if(strpos($string, ',') !== false || strpos($string, '"') !== false || strpos($string, "\n") !== false) {
        $string = '"' . str_replace('"', '""', $string) . '"';
    }
    return $string;
}
于 2013-05-16T17:54:45.187 回答