This is a basic function that accepts an array of data and an array of field names (column headers), and spits out a file for download. The two types of files are Excel and CSV.
The example is enclosed in a utility class that can contain a number of other functions, but you can just as easily use the function without the class wrapper.
<?php
class My_Utility {
function export_array_to_file($data, $field_names, $file_name = '', $file_type = 'EXCEL') {
switch (strtoupper($file_type)) {
case "EXCEL":
header("Content-type: "."application/x-msexcel");
$DELIMITER = "\t";
$file_ext = "xls";
break;
case "CSV":
header("Content-type: "."text/plain");
$DELIMITER = ",";
$file_ext = "csv";
break;
}
if (empty($file_name)) {
$file_name = "my_download_" . date('YmdHis') . "." . $file_ext;
}
else {
$file_name .= '.' . $file_ext;
}
/* Stream fputcsv to php output to send to the browser instead of saving as a file */
header("content-disposition: attachment; filename=".$file_name);
$outfile = fopen('php://output', 'w');
if (!is_array($field_names)) {
$field_names = explode(',', $field_names);
}
fputcsv($outfile, $field_names, $DELIMITER);
foreach($data as $row) {
fputcsv($outfile, $row, $DELIMITER);
}
fclose($outfile);
exit();
}
}
It’s worth noting that you shouldn’t name the first column “ID” if you are using the Excel format. This is because Excel thinks that text files starting with IDxxx are in SYLK Format, and it will not open correctly.