繁体   English   中英

强制PHP通过浏览器下载文件

[英]Forcing PHP to download file via browser

我目前正在尝试在用户的浏览器中下载文件,但到目前为止仍无法实现。

我在stackoverflow.com上查看了其他答案,到目前为止,还没有找到解决我的问题的方法。

我的过程如下:

我创建文件名和文件路径,然后设置标题:

$date = new DateTime();
$currentDateTime = $date->format("Y-m-d H:i:s");
$filename = "{$name}_{$currentDateTime}.csv";
$filepath = $rootfull . "/{$filename}";

// Set headers
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . $filepath . '"');
header('Content-Length: ' . filesize($filepath)); 
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Transfer-Encoding: binary");
header('Pragma: no-cache');

然后创建文件并开始写入文件:

// Write header
fputcsv($output, $header);
fputcsv($output, array()); // Empty line

// Write column names
$column_headers = array_keys(array_flip($columns));

foreach ($data as $row)
{
    fputcsv($output, $row);
}

echo readfile($filepath);
die();

生成文件并将其写入指定的位置(在本例中为/var/www/<project>/<filename>.csv没有向用户指示发生了任何事情。没有下载对话框,也没有任何内容。

如果有人发现我的代码或过程有问题,请指出,并建议提出一种更好的/替代的方法,欢迎任何帮助。

如果写入磁盘没有好处(缓存不足),则可能类似以下写入缓冲区的操作:

<?php

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="dump_' . date('Ymd') . '.csv"');
header("Pragma: no-cache");
header("Expires: 0");
$this->outputCSV($results);
exit(); //->

public function outputCSV($data, $useKeysForHeaderRow = true)
{
    if ($useKeysForHeaderRow) {
        array_unshift($data, array_keys(reset($data)));
    }
    $outputBuffer = fopen("php://output", 'w');
    foreach($data as $v) {
        fputcsv($outputBuffer, $v);
    }
    fclose($outputBuffer);
}
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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