PHP输出到文件下载而不在服务器上创建文件

时间:2013-05-16 17:51:08

标签: php arrays fopen output

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

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

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

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:8)

您可以使用

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

答案 1 :(得分: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;
}
相关问题