Created
January 21, 2016 22:42
-
-
Save kjbrum/2bf83a9f72a7d943e5e8 to your computer and use it in GitHub Desktop.
Convert an array to a CSV string.
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 an array to a CSV string. | |
* | |
* @param array $array The array to be converted | |
* @return string The newly created string | |
*/ | |
function array_to_csv( $array ) { | |
if(count( $array ) == 0 ) { | |
return null; | |
} | |
ob_start(); | |
$df = fopen( 'php://output', 'w' ); | |
fputcsv( $df, array_keys( reset( $array ) ) ); | |
foreach( $array as $row ) { | |
fputcsv( $df, $row ); | |
} | |
fclose( $df ); | |
return ob_get_clean(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment