Skip to content

Instantly share code, notes, and snippets.

@HoangPV
Created September 13, 2017 08:41
Show Gist options
  • Save HoangPV/aa5592fb4dfc92bfa57535ba90be02c6 to your computer and use it in GitHub Desktop.
Save HoangPV/aa5592fb4dfc92bfa57535ba90be02c6 to your computer and use it in GitHub Desktop.
Convert a multi-dimensional, associative array to CSV data
<?php
/**
* Convert a multi-dimensional, associative array to CSV data
* @param array $data the array of data
* @return string CSV text
*/
function str_putcsv($data) {
# Generate CSV data from array
$fh = fopen('php://temp', 'rw'); # don't create a file, attempt
# to use memory instead
# write out the headers
fputcsv($fh, array_keys(current($data)));
# write out the data
foreach ( $data as $row ) {
fputcsv($fh, $row);
}
rewind($fh);
$csv = stream_get_contents($fh);
fclose($fh);
return $csv;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment