Yii CSV export to browser getting reamed with log messages instead of data
I am trying to export a CSV to the browser using Yii and the CSV keeps being filled by Yii log messages.
header('Content-Description: File Transfer');
header('Content-Type: application/csv');
header('Content-disposition: attachment; filename=enrollmen开发者_C百科t_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();
Any ideas why this doesn't work properly?
yeah, I actually wrote an extension to do that: http://www.yiiframework.com/extension/csvexport/
Basically it amounts to calling exit, take a look at the last few lines of the example:
// 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();
I would suggest just killing the script after you've output everything. This prevents anything from being added to the output. A simple 'die' should do the trick.
You can use this code in your controller to disable all logging to the browser for all actions:
protected function beforeAction($action)
{
foreach (Yii::app()->log->routes as $route)
{
if ($route instanceof CWebLogRoute)
{
$route->enabled = false;
}
}
return true;
}
source
精彩评论