PHP output to file for download without creating file on the server

大憨熊 提交于 2019-12-30 11:13:12

问题


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.

Any help would be greatly appreciated!


回答1:


You can use

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



回答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";

etc Small function used by me to to optionally encode CSV fields::

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


来源:https://stackoverflow.com/questions/16594185/php-output-to-file-for-download-without-creating-file-on-the-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!