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.


<?php

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

// Now add the actual values under each column
$strCsv .= "Adeel,123455667,adeel@yahoo.com, Pakistan" . PHP_EOL;
$strCsv .= "Adam,1455454367,adam@hotmail.com, Singapore" . PHP_EOL;
$strCsv .= "Alex,15434556457,alex@yahoo.com, 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.

Please follow and like us:
error

Be the first to comment

Leave a Reply

Your email address will not be published.