PHP - 浏览器崩溃,浏览器无法以CSV格式输出

时间:2016-07-26 10:01:32

标签: php google-chrome csv

我有一个csv.phtml,其中包含所有行和列值

csv.phtml:

ID,column1,column2
1,french_words,dutch words
2,french_words,dutch words
10000,randrom words, random words

PHP:

$html = $this->view->render('print/csv.phtml');  
// this works, it prints $html       
//echo $html; 
//exit;     

// from here: it does not work 
$this->getResponse()
        ->setHeader('Content-Disposition', 'attachment; filename=report.csv')
        ->setHeader('Content-Type', 'application/csv')
        ->setBody($html)
        ->sendResponse();
exit;

enter image description here

我该如何解决? $ html中是否有一些奇怪的字符导致application / csv无法呈现?我怎么能找到那个无效的部分?

2 个答案:

答案 0 :(得分:1)

试试这个

$response = $this->getResponse();
$response->setContent($html);

$headers = $response->getHeaders();
$headers->clearHeaders()
    ->addHeaderLine('Content-Type', 'application/csv')
    ->addHeaderLine('Content-Disposition', 'attachment; filename=report.csv')
    ->addHeaderLine('Content-Length', strlen($html));


return $this->response;

答案 1 :(得分:-1)

为什么在我使用时如下工作:?

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo $html;
exit;

但是当我使用如下时不起作用?

$this->getResponse()
        ->setHeader('Content-Disposition', 'attachment; filename=report.csv')
        ->setHeader('Content-Type', 'application/csv')
        ->setBody($html)
        ->sendResponse();

exit;