File download issue in PHP with Content-Disposition: attachment

scott80109 picture scott80109 · Jun 8, 2012 · Viewed 8.2k times · Source

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?

Answer

drew010 picture drew010 · Jun 8, 2012

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.