CSV stands for 'comma-seperated-values.' These files are very commonly used to export and import data into different databases or Microsoft Excel.
Even though it it a relatively simple thing to do, I thought I would add it to my toolkit since it is something that I do quite frequently.
The nature of the format makes it so the file is very structured. The top row contains the field names, the rest of the rows are the records.
My thought was to just pass an array to a method and the browser will prompt the user to download the .csv file. Simple enough.
//file named CA_CSV.php class CA_CSV { public static function download($arrays, $filename = 'output.csv') { $string = ''; $c=0; foreach($arrays AS $array) { $val_array = array(); $key_array = array(); foreach($array AS $key => $val) { $key_array[] = $key; $val = str_replace('"', '""', $val); $val_array[] = "\"$val\""; } if($c == 0) { $string .= implode(",", $key_array)."\n"; } $string .= implode(",", $val_array)."\n"; $c++; } CA_FileDownload::download($string, $filename); } }
Now this method simply takes in the string of data and the name that you want to give the file that you will prompt the user to download.
<?php //File Named CA_FileDownload.php /** * File Download * * Many times you need to prompt somebody to download * the string of data you have as a file and name the file * for them. * * This isn't exactly rocket science... but it's handy. * * @author Kevin Korb */ Class CA_FileDownload { /** * Download * * Simply pass in the string of data you want to be * in the file and then the filename and it will * prompt the user to download it. (Just make sure * this is called before anything is transferred to the * browser. * * @param string $string * @param string $filename */ public static function download($string, $filename) { header("Pragma: public"); header("Expires: 0"); header("Cache-Control: private"); header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=$filename"); header("Accept-Ranges: bytes"); echo $string; exit; } } ?>
Now here is the demo code to test out our CSV Generator
$array_for_csv = array( array( 'id' => 3, 'name' => 'Kevin', 'position' => 'PHP Developer', 'city' => "St. Louis", 'state' => 'MO' ), array( 'id' => 5, 'name' => 'Billy', 'position' => 'Cook', 'city' => "St. Charles", 'state' => 'MO' ), array( 'id' => 349, 'name' => 'Freddy', 'position' => 'Painter', 'city' => "O'Fallon", 'state' => 'MO' ), ); CA_CSV::download($array_for_csv); ?>

Leave a Comment