Create a CSV File for a user in PHP
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")));
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;}
Here is an improved version of the function from php.net that @Andrew posted.
function download_csv_results($results, $name = NULL){ if( ! $name) { $name = md5(uniqid() . microtime(TRUE) . mt_rand()). '.csv'; } header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename='. $name); header('Pragma: no-cache'); header("Expires: 0"); $outstream = fopen("php://output", "wb"); foreach($results as $result) { fputcsv($outstream, $result); } fclose($outstream);}
It is really easy to use and works great with MySQL(i)/PDO result sets.
download_csv_results($results, 'your_name_here.csv');
Remember to exit()
after calling this if you are done with the page.