Skip to content

Instantly share code, notes, and snippets.

@carloscarucce
Last active October 31, 2016 14:11
Show Gist options
  • Save carloscarucce/cc2d38291c93c9057fd1cb768b0d786e to your computer and use it in GitHub Desktop.
Save carloscarucce/cc2d38291c93c9057fd1cb768b0d786e to your computer and use it in GitHub Desktop.
Exports associative array to xls file
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");;
header("Content-Transfer-Encoding: binary ");
header("Content-Disposition: attachment; filename=\"file.xls\"");
header("Pragma: no-cache");
header("Expires: 0");
$out = fopen("php://output", 'w');
$row = [/* Data to export */];
$flag = false;
foreach($rows as $data) {
if(!$flag) {
echo implode("\t", array_keys($data)) . "\n";
$flag = true;
}
//Filter data
array_walk($data, function (&$str) {
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if (strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
});
echo implode("\t", array_values($data)) . "\n";
}
fclose($out);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment