Yii CSV导出到浏览器,用日志消息代替数据


Yii CSV export to browser getting reamed with log messages instead of data

我正在尝试使用Yii导出CSV到浏览器,CSV一直被Yii日志消息填充。

header('Content-Description: File Transfer');
header('Content-Type: application/csv');
header('Content-disposition: attachment; filename=enrollment_course.csv');
$enrollment = Reports::getEnrollment($courseId);
$separator=",";
foreach ($enrollment as $users)
{
    $tmp = array(
        $users->userid,
        $users->firstname,
        $users->lastname,
        );
    echo join($separator, $tmp)."'n";
}
Yii::app()->end();

知道为什么这不能正常工作吗?

是的,我实际上写了一个扩展:http://www.yiiframework.com/extension/csvexport/

基本上相当于调用exit,看一下示例的最后几行:

// options for file, changing delimeter and enclosure
$content = $csv->toCSV('../myfilename.csv', "'t", "'");                 
Yii::app()->getRequest()->sendFile($filename, $content, "text/csv", false);
// call exit instead of letting sendFile do it, because if you are using
// CWebLogRoute, the onEndRequest event will fire and output your log and not csv file :(
exit();

我建议在输出完所有内容后终止脚本。这样可以防止向输出中添加任何内容。一个简单的"die"就可以了。

您可以在控制器中使用以下代码来禁用所有操作的浏览器记录:

protected function beforeAction($action)
{
        foreach (Yii::app()->log->routes as $route)
        {
                if ($route instanceof CWebLogRoute)
                {
                        $route->enabled = false;
                }
        }
        return true;
}