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!
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');
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;
}