Create a CSV File for a user in PHP
I have data in a MySQL database. I am sending the user a URL to get their data out as a CSV file.
I have the e-mailing of the link, MySQL query, etc. covered.
How can I, when they click the link, have a pop-up to download a CVS with the record from MySQL?
I have all the information to get the record already. I just don't see how to have PHP create the CSV file and let them download a file with a .csv extension.
Solution 1:
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
function outputCSV($data) {
$output = fopen("php://output", "wb");
foreach ($data as $row)
fputcsv($output, $row); // here you can change delimiter/enclosure
fclose($output);
}
outputCSV(array(
array("name 1", "age 1", "city 1"),
array("name 2", "age 2", "city 2"),
array("name 3", "age 3", "city 3")
));
php://output
fputcsv
Solution 2:
Try:
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo "record1,record2,record3\n";
die;
etc
Edit: Here's a snippet of code I use 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;
}