我有一个代码为的csv文件
// put data to file
$file = 'file.csv';
$fp = fopen($file, 'w');
foreach ($excel as $fields) {
fputcsv($fp, $fields);
}
//点击按钮下载文件:
if ($this->request->getPost('cvs')) { {
if (file_exists($file)) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=' . ($file));
header('Pragma: no-cache');
readfile('/var/www/admin/backend/public/' . $file);
// OR readfile($file);
}
}
file.csv中的数据(publuc文件夹中的file.csv):
[Time,A1,A7,A30
03/24/2015,42531,130912,315805
03/25/2015,41124,132746,319098
03/26/2015,41050,134858,320934
03/27/2015,38687,134679,321747]
但当我点击按钮下载文件时,下载的文件中的数据都是页面的html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">
<html xmlns=""http://www.w3.org/1999/xhtml"">...etc..
如何修复?非常感谢!
有点晚了,但我想每个人都错过了phalcon标签。缺少的是
$this->view->setRenderLevel('Phalcon'Mvc'View::LEVEL_NO_RENDER);
以下是我处理此问题的方法。
$this->response->resetHeaders();
$this->response->setHeader('Content-Type', 'application/csv');
$this->response->setHeader('Content-Disposition', 'attachment; filename='.$fileName);
$this->response->setContent($content);
return $this->response;
$content-对我来说,它是一个由数组组成的字符串,但你也可以使用file_get_contents()
我需要更多的信息来确定答案,但听起来浏览器只是被配置为将这种类型的下载保存为html。尝试使用另一个浏览器,或者更好地使用FTP客户端来获取文件,这样浏览器就不是一个因素。
如果您想继续使用浏览器,请尝试执行以下操作,而不仅仅是单击链接:
将鼠标放在链接上,然后右键单击。如果您可以选择"另存为",则将文件另存为.csv。如果您选择另存为.
使用content/Type作为
header('Content-Type: application/csv');
而不是header('Content-Type: text/csv');
You can also use the below two lines
header("Content-type: text/x-csv");
header("Content-type: application/csv");
If you want to set any particular file name to the download file then you can add
header("Content-Disposition: attachment; filename=dates_for_".date('dMy').".csv");