Not being prompted to download CSV file

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.

Related posts

Leave a Reply

4 comments

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

  2. 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';"/>
    
  3. 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');