Skip to content

Instantly share code, notes, and snippets.

@cam-gists
Created July 2, 2012 19:37
Show Gist options
  • Save cam-gists/3035200 to your computer and use it in GitHub Desktop.
Save cam-gists/3035200 to your computer and use it in GitHub Desktop.
PHP: generate CSV
<?php
function toCSV(array $data, array $colHeaders = array(), $asString = false) {
$stream = ($asString)
? fopen("php://temp/maxmemory", "w+")
: fopen("php://output", "w");
if (!empty($colHeaders)) {
fputcsv($stream, $colHeaders);
}
foreach ($data as $record) {
fputcsv($stream, $record);
}
if ($asString) {
rewind($stream);
$returnVal = stream_get_contents($stream);
fclose($stream);
return $returnVal;
}
else {
fclose($stream);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment