Last active
November 17, 2017 20:40
-
-
Save wtnabe/09580bcf6132589aeb2da2b8496c52a2 to your computer and use it in GitHub Desktop.
csv_encode.php
This file contains 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 | |
/** | |
* @param object $obj ( may be array ) | |
* @return mixed string or null | |
*/ | |
function csv_encode($obj) | |
{ | |
$csv = null; | |
$rows = is_object($obj) ? json_decode(json_encode($obj), true) : $obj; | |
if ( $rh = fopen('php://memory', 'w') ) { | |
fputcsv($rh, array_keys($rows[0])); | |
foreach ( $rows as $row ) { | |
fputcsv($rh, array_values($row)); | |
} | |
rewind($rh); | |
$csv = stream_get_contents($rh); | |
fclose($rh); | |
} | |
return $csv; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment