简体   繁体   中英

php file download in method is not working

I have a php class with a CSV creator and a file downloader that should download the file after creating the CSV. The CSV creator is working but the file downloader is not. I can not figure out why it is not downloading at all.

The code is below:

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;
    }
}

Try this

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

Just try this code

$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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM