在 Zend 框架中导出 csv

2021-12-29 00:00:00 csv php zend-framework

我正在尝试将数据库表导出为可从浏览器下载的 .csv.我的代码是基于 zend 框架的,我几乎可以通过以下操作实现:

I'm trying to export a database table as a .csv downloadable from the browser. My code is zend framework based and I'm almost there with the following action:

public function exportTableAction()
{
    $this->_helper->layout->disableLayout();
    $this->_helper->viewRenderer->setNoRender();

    $fileName = $this->_getParam('fileName');
    $tableName = $this->_getParam('tableName');       

    header('Content-type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.$fileName.'"');

    echo $this->getCsv($tableName, $fileName);
}

我可以下载包含有效数据的 .csv 文件.但是,即使我禁用了布局和渲染器,我仍然会在 .csv 文件的末尾获得页面的页眉、侧边栏和页脚的输出.有没有办法禁用除我的 exportTableAction 中生成的输出之外的任何 html 输出?或者我可以用不同的方式将标题信息和 csv 字符串发送到浏览器吗?

I can download my .csv file containing valid data. However, even if I disabled the layout and the renderer, I still get the output of the header, sidebar, and footer of my page at the end of my .csv file. Is there a way to disable any html output other than the one generated in my exportTableAction? Or can I send the header information and the csv string to the browser in a different way?

顺便说一句:我正在使用操作堆栈插件来帮助我呈现标题和侧边栏,如下所示:

BTW: I'm using the action stack plugin to help me render the header and sidebar as follows:

...
$actionStack = $front->getPlugin('Zend_Controller_Plugin_ActionStack');
$actionStack->pushStack($userlogAction);
$actionStack->pushStack($rightcolAction);

干杯,阿德里安

推荐答案

我们找到了问题的解决方案.我替换了以下行

We found a solution to the problem. I replaced the following line

$this->_helper->viewRenderer->setNoRender();

$this->_helper->viewRenderer->setNeverRender();

如果使用 setNeverRender(),则不会渲染任何视图(也不来自插件).

If setNeverRender() is used, no views are rendered (from plugin neither).

相关文章