CSV Export Using PHP’s Output Buffer

Creating the CSV file without using adding/deleting a file on the server’s file system. This involves the use of the PHP output buffer. In the case of a CSV file, they are being created by the PHP script on the fly, adding the data that you want to export on a row-by-row basis. For this we need to:

1) create a file handle
2) fputcsv each row into the file
3) send the entire thing to the browser to be downloaded

Here is the code:

header("Content-type: text/csv");
header("Cache-Control: no-store, no-cache");
header('Content-Disposition: attachment; filename="filename.csv"');

$outstream = fopen("php://output",'w');

foreach( $myArray as $row ) {
	fputcsv($outstream, $row, ',', '"');


$myArray is an array of records just the same as you would find in a database (the same thing that will appear in the new, downloaded CSV file). Notice that there is no file being created on the server.

Helpful tip:

Just relying on the extension doesn’t work, even in Windows. The magic is in the third header setting, “Content-Disposition,” which informs the browser to download as a separate file
~ from ToSweetToBeSour.com