How to download data as a CSV file using PHP

PHP has a very good function fgetcsv to read a CSV file and return each column as an array for processing in the code. However there is no similar function to convert the same data into a CSV file. You will actually have to write some PHP code for this purpose. Check the following code which will demonstrate this process. You can then tailor the code according to your needs.


// Set the column headers
$strCsv = "Name, Phone, Email, Country";

// Now add the actual values under each column
$strCsv .= "Adeel,123455667,[email protected], Pakistan" . PHP_EOL;
$strCsv .= "Adam,1455454367,[email protected], Singapore" . PHP_EOL;
$strCsv .= "Alex,15434556457,[email protected], Australia" . PHP_EOL;

//Finally comes the code which will force the browser to download this string of data as a CSV file
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename="customer-data.csv"");
echo $strCsv;

That’s it. Now when you run this script it will start downloading the CSV sheet on your computer.

If you would like to download the code for this file then please click here.

Hope the above helped in understanding this concept.

Leave a Comment