I found the function below online somewhere that is supposed to get some mysql data and download it as CSV/Excel. It sort of works, but instead of triggering a file download in the user's browser, it simply dumps the data into the end of the response stream and displays at the bottom of the browser window after all my other page contents. What am I doing wrong?
IMPORTANT: If I change from Excel content-type to CSV, it makes no difference and I get the same result, although technically it's creating CSV content and not really Excel content.
function DownloadQueryToCSV($sql, $filename){
$result = mysql_query($sql) or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
$file_ending = "xls";
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
$sep = "\t"; //tabbed character
for ($i = 0; $i < mysql_num_fields($result); $i++) {
echo mysql_field_name($result,$i) . "\t";
}
print("\n");
while($row = mysql_fetch_row($result))
{
$schema_insert = "";
for($j=0; $j<mysql_num_fields($result);$j++)
{
if(!isset($row[$j]))
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
else
$schema_insert .= "".$sep;
}
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
}
die(); // WARNING: Must die at end of function, else other page contents will end up in spreadsheet!!
}
Possible duplicates
This is not related to Excel, and in my view is not a duplicate of mysql to excel formatting issues