Snippets → PHP → Generate CSV from Array Generate CSV from Array Chris Coyier on Nov 25, 2009 function generateCsv($data, $delimiter = ',', $enclosure = '"') { $handle = fopen('php://temp', 'r+'); foreach ($data as $line) { fputcsv($handle, $line, $delimiter, $enclosure); } rewind($handle); while (!feof($handle)) { $contents .= fread($handle, 8192); } fclose($handle); return $contents; } Usage $data = array( array(1, 2, 4), array('test string', 'test, literal, comma', 'test literal "quotes"'), ); echo generateCsv($data); // outputs: // 1,2,4 // "test string","test, literal, comma","test literal""quote"""
Ok this is a sweet function!
This is very helpful. I realize that this is an older post, but I wanted to point out that it appears that you haven’t declared the variable
$contents
prior to appending to it.Awesome, thanks!
This is what they have now in php
http://php.net/manual/en/function.fputcsv.php
This guy added a nice touch – array keys as header
write out the headers
fputcsv($fh, array_keys(current($data)));
https://coderwall.com/p/zvzwwa/array-to-comma-separated-string-in-php
Writing a file just to transform array to CSV is very resource heavy and slow. This is similar approach, but uses only memory: https://coderwall.com/p/zvzwwa/array-to-comma-separated-string-in-php