Skip to content

Instantly share code, notes, and snippets.

@storkontheroof
Created March 20, 2019 07:42
Show Gist options
  • Save storkontheroof/f0426fa0ab0d1c70ffd39198448e89a8 to your computer and use it in GitHub Desktop.
Save storkontheroof/f0426fa0ab0d1c70ffd39198448e89a8 to your computer and use it in GitHub Desktop.
Function to export an array to 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