来自服务器的php下载文件无法正常工作

时间:2018-05-01 07:36:04

标签: php

我有这个代码在我的其他项目上工作,但现在下载文件是在浏览器上显示文件

$query = "SELECT * FROM leads";
$result = $dbconn->query($query);

$filename = "leads_shaldor_" . date("Y-m-d H:i");
$filepath = "/var/www/vhosts/as7.co.il/shaldor.as7.co.il/exports/" 
.$filename. ".csv";
    $downpath = "http://shaldor.as7.co.il/exports/" .$filename. ".csv";
    $csvFile = fopen($filepath, 'w') or die("can't open file");
    fprintf($csvFile, chr(0xEF).chr(0xBB).chr(0xBF));
    while($row = $result->fetch_assoc()){
        fputcsv($csvFile, 
array($row['id'],$row['name'],$row['phone'],$row['date']));
        print_r($row);
    }
    fclose($csvFile);
    header("Location: " . $downpath);


$result->close();
$sql->close();

3 个答案:

答案 0 :(得分:0)

$downpath = "http://shaldor.as7.co.il/exports/" .$filename. ".csv";
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"" . basename($downpath) . "\"")

设置以下标题。它应该强制下载。您的浏览器正在打开它,因为它知道如何呈现文件。

答案 1 :(得分:0)

参考这个答案:Forcing to download a file using PHP

header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=example.csv');
header('Pragma: no-cache');
readfile("/path/to/yourfile.csv");

答案 2 :(得分:-1)

你可以使用这个。

要强制下载服务器上的所有CSV文件,请添加.htaccess文件:

AddType application/octet-stream csv

PHP解决方案

header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=example.csv');
header('Pragma: no-cache');
readfile("/path/to/yourfile.csv");