简体   繁体   中英

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=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();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM