我正在尝试将数据库表导出为可从浏览器下载的.csv。我的代码是基于zend框架的,我几乎可以执行以下操作:
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输出之外的任何html输出?或者我可以以不同的方式将标题信息和csv字符串发送到浏览器吗?
BTW:我正在使用动作堆栈插件来帮助我渲染标题和侧边栏,如下所示:
...
$actionStack = $front->getPlugin('Zend_Controller_Plugin_ActionStack');
$actionStack->pushStack($userlogAction);
$actionStack->pushStack($rightcolAction);
干杯,阿德里安
答案 0 :(得分:7)
我们找到了解决问题的方法。我替换了以下行
$this->_helper->viewRenderer->setNoRender();
通过
$this->_helper->viewRenderer->setNeverRender();
如果使用setNeverRender(),则不会渲染任何视图(也不会从插件中渲染)。
答案 1 :(得分:6)
您可以使用contextSwitch动作帮助程序。
public $contexts = array(
'test' => array('csv')
);
public function testAction()
{
$filename = time() . '.csv';
$this->_helper->contextSwitch()->addContext('csv',
array('suffix' => 'csv',
'headers' => array('Content-Type' => 'application/csv',
'Content-Disposition' => 'attachment; filename="'. $filename.'"')))->initContext('csv');
........................
........................
}
答案 2 :(得分:1)
$this->_helper->viewRenderer->setNoRender();
$this->view->layout()->disableLayout();
$response = $this->getResponse();
$response->setHeader('Content-type', 'application/octet-stream');
$response->setHeader('Content-Disposition', 'attachment; filename="contatos.csv"');
echo $your_csv_content;
答案 3 :(得分:0)
public function getCsv($tableName, $fileName)
{
$content = new $tableName();
$content_arr = array();
$content_arr = $content->fetchAll('1=1','id ASC');
$csv_terminated = "\n";
$csv_separator = ",";
$csv_enclosed = '"';
$csv_escaped = "\\";
$schema_insert = "";
$l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
stripslashes("Email Address")) . $csv_enclosed;
$schema_insert .= $l;
$schema_insert .= $csv_separator;
$l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
stripslashes("Add Date")) . $csv_enclosed;
$schema_insert .= $l;
$schema_insert .= $csv_separator;
$out = trim(substr($schema_insert, 0, -1));
$out .= $csv_terminated;
if(count($content_arr) > 0)
{
foreach($content_arr as $content)
{
$schema_insert = '';
if ($content->email != '' || $content->add_date != '')
{
$schema_insert .= $csv_enclosed .
str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $content->email) . $csv_enclosed;
$schema_insert .= $csv_separator;
$schema_insert .= $csv_enclosed .
str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $content->add_date) . $csv_enclosed;
$schema_insert .= $csv_separator;
}
$schema_insert .= $csv_separator;
$out .= $schema_insert;
$out .= $csv_terminated;
}
}
return $out;
}`