views:

71

answers:

4

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.

A: 

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');
Dolph
+2  A: 

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.

jordanstephens
Thank you for the help on this!
hsatterwhite
+4  A: 

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...

ircmaxell
Worked great! Thanks for the resource link as well!
hsatterwhite
+1  A: 

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';"/>
typoknig
Nice solution, I appreciate your help! :)
hsatterwhite