Since the MS Excel is not able to recognize CSV files as of utf-8 encoding i tried to manually create such a file prepending the BOM prefix. But in my case i need to send it for user/browser to open rather than to save it on disk.
The trick is that with small amount of data ~1-10 it works well, yet when of bigger number of records to be out, it fails to output in browser (Google Chrome, FF), rather it prints result as an HTML. You might try to play with it varying count
parameter in GET request: http://tarex.ru/index.php?r=user/pricelist&file=1&count=100
The code
$limit = $_GET['count'] ? $_GET['count'] : 10;
$filename= 'test.csv';
$out = fopen('php://output', 'w'); // open to out in browser
fwrite($out, "\xEF\xBB\xBF"); // prepend BOM
$counter=0;
foreach(Assortment::model()->findAll( 'measure_unit<>"" AND price>0' ) as $d)
{
$arr = array( $d->article2, $d->title, $d->oem, $d->make, $d->availability , $d->getPrice(Yii::app()->user->id), $d->getDiscountOpt(Yii::app()->user->id) );
fputcsv($out, $arr, ';'); //delimiter - ;
if ($counter++ > $limit) break;
}
header('Content-type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
fclose($out);
Is there any solution?
Update
Eventually i've done it with Yii::app()->request->sendFile
after turutosiya's suggestion.
$filename='test.csv';
$filepath = Yii::app()->basePath . '/../files/'. $filename;
$out = fopen($filepath, 'w');
// writing csv ...
fwrite($out, "\xEF\xBB\xBF"); // put BOM at the beginning of file
fputcsv($out, $arr, ';');
foreach(Assortment::model()->findAll() as $d)
{
$arr = array( $d->article2, $d->title, $d->oem, $d->make, $d->availability);
fputcsv($out, $arr, ';'); // separator - ;
}
fclose($out);
Yii::app()->request->sendFile($filename, @file_get_contents($filepath));