【问题标题】:php file download in method is not working方法中的php文件下载不起作用
【发布时间】:2018-04-08 14:44:48
【问题描述】:

我有一个带有 CSV 创建器和文件下载器的 php 类,它应该在创建 CSV 后下载文件。 CSV 创建器正在工作,但文件下载器没有。我不知道为什么它根本没有下载。

代码如下:

class Orders
{
    public $pdoLink,
           $timestamp;


    public function __construct()
    {
        include_once "connect.php";
        $this->pdoLink = $pdo;
        $this->timestamp = date("Y-m-d-h_i_s_a",time());
    }

    public function createCsv($begindate = false, $endDate = false)
    {

        $list = (($begindate) && ($endDate)) ? $this->getOrders($begindate,$endDate) : $this->getOrders();

        $file_name = "orders_" . $this->timestamp . ".csv";
        $file = fopen($file_name,"w");

        foreach ($list as $line)
        {
            fputcsv($file,explode(',',$line));
        }
        $this->downloadCsv($file_name);

    }
    public function downloadCsv($file)
    {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.urlencode($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
        exit;
    }
}

【问题讨论】:

  • 尝试将您的内容类型标头更改为header('Content-Type: text/csv');

标签: php csv download


【解决方案1】:

试试这个

$file = urlencode($file);
header('Content-Type: text/csv; charset=utf-8');
header("Content-Disposition: attachment; filename=\"$file\"");

【讨论】:

  • 能否请您尝试删除干净的输出缓冲区和刷新功能......删除ob_clean()flush()
【解决方案2】:

试试这段代码

$filename = "file.csv";
        $fp = fopen('php://output', 'w');
        header('Content-type: application/csv');
        header('Content-Disposition: attachment; filename='.$filename);
        fputcsv($fp, $header_data);
        fclose($fp);
        exit;

【讨论】:

  • 这不会创建文件的下载。
猜你喜欢
  • 2012-11-26
  • 2015-08-07
  • 1970-01-01
  • 2014-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-16
  • 2012-01-05
相关资源
最近更新 更多