Skip to content

Instantly share code, notes, and snippets.

@cam-gists
Created August 20, 2012 16:02
Show Gist options
  • Select an option

  • Save cam-gists/3405377 to your computer and use it in GitHub Desktop.

Select an option

Save cam-gists/3405377 to your computer and use it in GitHub Desktop.
PHP: Array to CSV
<?php
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;
}
$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"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment