PHP输出到文件以供下载,而无需在服务器上创建文件

问题描述:

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

I would like to output my data to a file for the user to download without actually creating the file physically on the server. The data of the file is simply array that I'm converting into a CSV format for the user to download. Here's my code:

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

上面的代码成功创建了文件...但是我不想创建一个文件.我只想流输出.

The above code creates the file successfully... but I don't want to have to create a file. I want to simply stream the output.

任何帮助将不胜感激!

您可以使用

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