繁体   English   中英

用php下载csv文件

[英]download csv file with php

我有一个带代码的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。 如果选择另存为,它将自动为您选择.csv。

将内容/类型用作

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");

暂无
暂无

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

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