Skip to content

Instantly share code, notes, and snippets.

@dcblogdev
Created June 13, 2013 12:13
Show Gist options
  • Save dcblogdev/5773211 to your computer and use it in GitHub Desktop.
Save dcblogdev/5773211 to your computer and use it in GitHub Desktop.
Export from MySQL to Excel
<?php
function cleanData($str){
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\n/", "\\n", $str);
}
$filename = "export_" . date('Y-m-d-h-i-s') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
$result = mysql_query("SELECT * FROM table") or die('Query failed!');
while(false !== ($row = mysql_fetch_assoc($result))) {
if(!$flag) {
# display field/column names as first row
echo implode("\t", array_keys($row)) . "\n";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t", array_values($row)) . "\n";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment