繁体   English   中英

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

[英]PHP output to file for download without creating file on the server

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

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

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

任何帮助将不胜感激!

您可以使用

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

echo "record1,record2,record3\n";

等我使用的用于选择编码CSV字段的小function ::

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM