简体   繁体   中英

PHP/MYSQL to CSV Export code printing to screen instead of CSV file

I can't get the browser to prompt for download. The output gets displayed on the screen instead. I've tried so many other threads regarding this topic on this site but to no avail. I could change the fopen("php://output","w") to fopen("export.csv","w") but that will save a copy of the export.csv file on the server, which I don't want. I want the file to be downloaded on the client without it being saved on the server. Here's my code:

$sql = mysql_query($_SESSION["export-query"]);
$fields = mysql_num_fields($sql);
$header = array();

for ($i = 0; $i < $fields; $i++) {
    $header[] = mysql_field_name($sql, $i);
}

$f = fopen("php://output","w"); 
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=export.csv');
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate');
fputcsv($f, $header);

while ($row = mysql_fetch_row($sql)) {
    fputcsv($f, $row);
}
fclose($f);

Please help! Much appreciated.

Your code is really close to mine, but I have this

header("Content-type: application/vnd.ms-excel");

for the content type. I think this works because browsers know how to handle text/csv but they don't know how to handle excel. It will prompt to download because it doesn't open this type of file itself.

I also don't have "must-revalidate," but I don't think that makes a difference.

EDIT:

Here are my full headers, which have worked 100% of the time. There are minor differences from yours, so maybe one of them is the reason.

    header("Content-type: application/vnd.ms-excel");
    header("Content-disposition: attachment; filename=".$filename.".csv");
    header("Pragma: no-cache");
    header("Expires: 0");

EDIT 2:

Judging from your comment on your answer, you are putting all of this code as an ajax call inside a div. The reason that doesn't work is that you can only set headers on the initial call to a page. Setting headers on an ajax call will be ignored.

Here is how my system handles csv generation. Because I needed specific information that could vary between different csv files, I put the name of the generator file into the "action" of a form and provided a submit button:

<form action="thegeneratorpage.php" method="get"><fieldset>
     <p>Download [...] in .csv (Excel) form.  You can narrow by [...].</p>
     <!-- code here that allows users to narrow down what is in the csv -->
     <input type="submit" value="Download" />
</fieldset></form>

If the information doesn't vary, you can just do this:

<a href="thegeneratorpage.php">Download CSV</a>

All the code we have been discussing would be on thegeneratorpage.php .

Rather than using the fputcsv function, I would suggest just echoing the rows of the CSV file like so (note that the headers I use are slightly different from yours):

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename={$fileName}");
header("Content-Transfer-Encoding: binary");
while ($row = mysql_fetch_row($sql)) {
    // optionally enclose data if necessary
    foreach ($row as $k => $v) {
        if (strpos($v, ',') !== false) {
            $row[$k] = '"' . $v . '"';
        }
    }
    echo implode(',', array_values($row));
}

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