dongxietao0263 2012-06-08 09:16
浏览 637
已采纳

使用Content-Disposition:附件的PHP中的文件下载问题

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?

  • 写回答

3条回答 默认 最新

  • duanjie9630 2012-06-08 17:12
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突