Skip to content

Instantly share code, notes, and snippets.

@wtnabe
Last active November 17, 2017 20:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wtnabe/09580bcf6132589aeb2da2b8496c52a2 to your computer and use it in GitHub Desktop.
Save wtnabe/09580bcf6132589aeb2da2b8496c52a2 to your computer and use it in GitHub Desktop.
csv_encode.php
<?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