Created
August 19, 2017 08:20
-
-
Save ontiuk/627c35d32acc4a154928e40c912d9ee5 to your computer and use it in GitHub Desktop.
Array to CSV with 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
/** | |
* Array to CSV | |
*/ | |
function array2csv( $array) { | |
// Check input | |
if ( !is_array( $array ) || count( $array ) == 0 ) { return null; } | |
// Buffer output | |
ob_start(); | |
$df = fopen("php://output", 'w'); | |
fputcsv($df, array_keys( reset($array) ) ); | |
foreach ($array as $row) { | |
fputcsv($df, $row); | |
} | |
fclose($df); | |
// return constructed csv with header | |
return ob_get_clean(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment