Created
September 13, 2017 08:41
-
-
Save HoangPV/aa5592fb4dfc92bfa57535ba90be02c6 to your computer and use it in GitHub Desktop.
Convert a multi-dimensional, associative array to CSV data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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