Not being prompted to download CSV file

2019-07-16 15:14发布

问题:

I've created a custom solution in WordPress that will generate a CSV file to be downloaded by clicking a simple hyperlink, linked directly to this file. Instead of being prompted to download the file to the computer; the CSV opens in the the browser window instead.

FWIW I'm on Media Temple using a vanilla install of WordPress.

回答1:

Send the proper mime type

header('Content-type: text/csv');

And use the Content-Disposition header to tell it to download: http://www.jtricks.com/bits/content_disposition.html

header('Content-Disposition: attachment; filename="mycssfile.csv"');

You always want to send the proper mime type, otherwise firewalls, anti-virus software and some browsers may have issues with it...



回答2:

You can use PHP's header() function to change Content-type

header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="myFile.csv"');

The above code will force a prompt to the user for download. where myFile.csv should be replaced with the path to the file you want downloaded.



回答3:

This works:

$filename = 'export.csv';
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);

Also, I personally do not like links on my sites, I like buttons. If you want a button to do for the export function you can use the code below. I just thought I would post it because it took me a bit to figure out the first time :)

<input type="button" value="Export to CSV" onClick="window.location.href='something.php?action=your_action';"/>


回答4:

You need to send the browser a MIME type of application/csv so it will offload the responsibility of handling the file to whatever the OS recommends (or user chooses).

In PHP (before any output is sent to the client):

header('Content-type: application/csv');