0

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!!
}

Moderator: This has nothing to do with Excel, and is not a duplicate of mysql to excel formatting issues

HerrimanCoder
  • 5,858
  • 20
  • 65
  • 111

1 Answers1

0

Try using the Excel content type listed here: What is a correct mime type for docx, pptx etc?

 .xls      application/vnd.ms-excel

If that isn't enough, try adding this (though I realize CSV is text):

 Content-Transfer-Encoding: binary
Dave S
  • 1,283
  • 1
  • 13
  • 16
  • Thanks. Another problem I had was streaming down the file after other page content had loaded. Once I stream down the file before any page content, it worked fine. – HerrimanCoder May 30 '17 at 11:24