Posted By

welancers on 08/22/12


Tagged

php csv generate


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

tux-world


Generate CSV file from Array using PHP


 / Published in: PHP
 

Very simple & short code snippet which is very useful at many places to generate CSV files.

Usage :

$data = array( array(1, 2, 4), array('test string', 'test, literal, comma', 'test literal "quotes"'), );

echo generateCsv($data);

  1. function generateCsv($data, $delimiter = ',', $enclosure = '"') {
  2. $handle = fopen('php://temp', 'r+');
  3. foreach ($data as $line) {
  4. fputcsv($handle, $line, $delimiter, $enclosure);
  5. }
  6. rewind($handle);
  7. while (!feof($handle)) {
  8. $contents .= fread($handle, 8192);
  9. }
  10. fclose($handle);
  11. return $contents;
  12. }

Report this snippet  

You need to login to post a comment.