Skip to content

Instantly share code, notes, and snippets.

@ontiuk
Created August 19, 2017 08:20
Show Gist options
  • Save ontiuk/627c35d32acc4a154928e40c912d9ee5 to your computer and use it in GitHub Desktop.
Save ontiuk/627c35d32acc4a154928e40c912d9ee5 to your computer and use it in GitHub Desktop.
Array to CSV with PHP
/**
* 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