简体   繁体   中英

How to correct filename value in Content-Disposition header?

This piece of code NEARLY solves my issue saving a query to .csv via php – however I can't understand why when it prompts me to save as export.csv , that file opens blank, while file.csv saves perfectly at the same time with the data I need. I'm sure it's something obvious going on with the headers. Can anyone help?

***EDIT below suggestions got me to this state and it no longer saves a file and prompts for a blank one but now the correct file shows with HTML crap in it. There is no other HTML in this script -- I've tried suggestions from many other posts. How can I solve?

$query = "SELECT * from Table";

$result = mysqli_query($connS, $query);

   $headers = $result->fetch_fields();
foreach($headers as $header) {
    $head[] = $header->name;
}
$fp = fopen('php://output', 'w');

header('Content-Disposition: attachment; filename="export.csv"');
header('Content-Description: File Transfer');
header('Content-Type: text/csv');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
    fputcsv($fp, array_values($head)); 
    while ($row = $result->fetch_array(MYSQLI_NUM)) {
        fputcsv($fp, array_values($row));
    }
    $fp = fopen('file.csv', 'w');
    readfile($fp);
    fclose($fp);

end();

You're currently only saving the contents to file, not sending it to the user's browser. Perhaps try adding a call to readfile before your die statement.

So your last rows would look like this:

    while ($row = $result->fetch_array(MYSQLI_NUM)) {
        fputcsv($fp, array_values($row));
    }
    readfile($fp);
    die; 
}

Readfile reads a file and writes it to the output buffer. You can find more information on the readfile function here .


Note that the way you're currently doing it(saving to file before the user can download), if two users hit that page simultaneously, they would likely stomp on each others' toes(and create some odd intermix of the two created CSVs). You may want to try simply outputting the CSV contents directly to the user's browser , using the code in the accepted answer there. If you do that after your headers, it should result in the browser treating it like a file to be downloaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM