Skip to content

Instantly share code, notes, and snippets.

@wpscholar
Last active June 7, 2020 04:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wpscholar/1661294 to your computer and use it in GitHub Desktop.
Save wpscholar/1661294 to your computer and use it in GitHub Desktop.
Takes an array of data and create a csv file that will automatically download
<?php
/**
* Takes an array of data and creates a csv file that will automatically download
*/
function downloadable_csv( $data, $filename = 'data_csv' ){
/*
Sample Data Format:
array(
'headings' => array(),
'data' => array(
array()
)
);
*/
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename='.$filename.'.csv');
// Create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// Output the column headings
fputcsv($output, $data['headings']);
// Loop over the rows, outputting them
foreach( $data['data'] as $row ){
fputcsv($output, $row, ',', '"');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment