Zend Framework 2 - 呈现CSV数据 [英] Zend Framework 2 - Rendering CSV data
问题描述
我有一个模型,返回汽车数据的id,名称,价格等。所以我有一个汽车控制器和csv动作从模型中获取这些数据:
i have a model that returns car data with id, name, price etc. So i have a car controller and a csv action that fetches this data from a model:
$carTable = $this->getServiceLocator()->get('Application\Model\DbTable\Cars');
$cars = $carTable->fetchAll();
我需要将这个$ cars数据下载为CSV文件,
i need to download this "$cars" data as a CSV file, so the user can store it on the disk.
我试图禁用布局并回显CSV字符串并设置content-type和其他标题,但它没有工作盒子。然后我想出,我应该创建一个自定义的CsvRenderer并在配置中注册它。
I have tried to disable the layout and echo a CSV string and setting "content-type" and other headers, but it didn't work out of the box. Then i figured out that i should probably create a custom CsvRenderer and register it in configuration.
由于我在ZF2网站或博客和Stackoverflow答案找不到任何文档,我想知道这是否是推荐的一般方法下载数据在ZF2中为CSV?或者有一个更简单的解决方案,我不知道?
Since i couldn't find any documentation about this on the ZF2 site or in blogs and Stackoverflow answers, i would like to know if this is the recommended general approach for downloading data as CSV in ZF2? or is there a simpler solution that i am not aware of?
感谢
推荐答案
一个解决方案是直接从控制器返回一个Response对象。
One solution would be to return a Response object directly from the controller.
这样的工作机会很大:
public function downloadAction()
{
// magically create $content as a string containing CSV data
$response = $this->getResponse();
$headers = $response->getHeaders();
$headers->addHeaderLine('Content-Type', 'text/csv');
$headers->addHeaderLine('Content-Disposition', "attachment; filename=\"my_filen.csv\"");
$headers->addHeaderLine('Accept-Ranges', 'bytes');
$headers->addHeaderLine('Content-Length', strlen($content));
$response->setContent($content);
return $response;
}
(请注意,我没有测试此代码, with comment!)
(Note that I haven't tested this code, but have updated in line with comment!)
这篇关于Zend Framework 2 - 呈现CSV数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!