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@example.com, Pakistan" . PHP_EOL;
$strCsv .= "Adam,1455454367,firstname.lastname@example.org, Singapore" . PHP_EOL;
$strCsv .= "Alex,15434556457,email@example.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-Disposition: attachment; filename=\"customer-data.csv\"");
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.