【发布时间】:2016-06-14 15:04:29
【问题描述】:
我目前正在开发一个使用 Zend 框架的 PHP 项目。我正在制作一个 CSV,在控制器中没有任何问题,但是希望用户能够通过单击视图中的按钮来下载文件。
在我的.phtml 我有:
<a class="btn" href="<?php echo $this->download;?>" download>Export to CSV</a>
$this->download 正在控制器中设置:
$view["download"] = $this->_createCSV($bqc_jobs, $startDate, $endDate, $processor_id, $defaultTime);
_createCSV 函数创建 CSV 并将其存储在站点使用的临时目录中。然后它返回文件路径。
private function _createCSV($jobs, $start, $end, $user=null, $minutes){
$format = "Ymd_His";
if(!$start && !$user){
$start = date($format, strtoTime("-" . $minutes . " minutes"));
}
if(!$end){
$end = \DateTime::createFromFormat($format, date($format))->format($format);
}
$directory = Config::$tempDir;
$fileName = $directory . "/" . ($user ? $user . "_" : "") . ($start ? $start . "_" : "") . $end . "_report.csv";
$file = fopen($fileName, 'w');
foreach ($jobs as $job){
fputcsv($file, $job);
}
fclose($file);
return $fileName;
}
单击按钮时,浏览器尝试下载文件,但由于找不到文件而出错。这是有道理的,因为浏览器不应该访问临时文件夹,但我不完全确定如何解决这个问题。
【问题讨论】:
-
在 Laravel 中,我最近通过流式传输文件实现了完全相同的目标 - 我快速搜索了一下 google,发现这可能会有所帮助(不熟悉 zend)sasaprolic.com/2013/02/sending-stream-responses-with-zend.html
-
@Djave 看起来很有希望,谢谢
标签: php csv zend-framework download