0

I read a whole bunch of articles in SO and the internet and tried all of them but I am still unable to create a CSV download functionality in PHP.

Following is my code:

$csvData = @$_POST['csv_data'];
if(trim($csvData))
{
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header('Content-Description: File Transfer');
    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename=data.csv");
    header("Expires: 0");
    header("Pragma: public");
    echo $csvData;
    exit;   
}

Instead of showing the file save dialog, this keeps printing the CSV data into my browser :( What am I doing wrong here? Any help is much appreciated..

Additional Edit: I am posting this data into my script, which immediately takes this data and tries to download. My script is an include inside another file, will that be a problem? I enabled error_reporting and found that I am getting header already modified error...

Undefined Variable
  • 4,196
  • 10
  • 40
  • 69

1 Answers1

0

In HTTP, headers are sent before any text output.

For that reason, PHP will close your response header if you output any text.

Make sure that you hold any text output before your header modification, for example using the OB-cache.

BlackCetha
  • 2,051
  • 1
  • 15
  • 15