5

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!

Andrew
  • 2,691
  • 6
  • 31
  • 47

2 Answers2

18

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');
brbcoding
  • 13,378
  • 2
  • 37
  • 51
  • Just add these headers and open to `php://output` instead of the file. – brbcoding May 16 '13 at 17:56
  • One thing though: When I write to the server, the CSV file looks good. When I output to download, the CSV file is basically just the source of the webpage. It's outputting everything on screen I guess and not just the array (as per my code above). Any ideas? – Andrew May 16 '13 at 18:03
  • Yeah, you'll have to run through a `foreach` on the array, line by line with `fputcsv()`. Let me know if that doesn't make sense and I'll add another example. – brbcoding May 16 '13 at 18:06
  • 1
    I just outputted to a new window that downloads the file and it works fine. Thanks for the help! – Andrew May 16 '13 at 18:24
3
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;
}
Kailash Yadav
  • 1,880
  • 2
  • 18
  • 37