Question

I have a link on my web page to download a .CSV file that I have generated on the server. The code for the download is as follows:

//open/save dialog box
header('Content-Disposition: attachment; filename="inventoryData.csv"');
//content type
header('Content-type: application/excel');
//read from server and write to buffer
readfile('spreadsheet/inventory.csv');

When I open the file on the server, it looks just fine. However, when I download the file via the dialog box, it is pre-pending the HTML code for the web page to the .csv file.

Any ideas why that would happen?

Was it helpful?

Solution

If this code is in a controller action which I assume it is since you are using ZF, then you need to disable your layout and the view renderer as it will try to render a view.

Try:

public function downloadAction()
{
    $this->_helper->layout()->disableLayout();
    $this->_helper->viewRenderer->setNoRender(true);

    //...

    //open/save dialog box
    header('Content-Disposition: attachment; filename="inventoryData.csv"');
    //content type
    header('Content-type: application/excel');
    //read from server and write to buffer
    readfile('spreadsheet/inventory.csv');
}

$this->_helper->layout()->disableLayout(); prevents your layout script from being rendered (assuming you use layouts), and $this->_helper->viewRenderer->setNoRender(true); tells the view renderer not to render the view script for the controller action which may contain some HTML or whitespace.

OTHER TIPS

This should do the trick

  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=\"inventoryData.csv\";" );
  header("Content-Transfer-Encoding: binary");

Try this one:

header("Content-type: application/octet-stream");
header("Content-disposition:attachment; filename=inventoryData.csv");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top