itnelo
itnelo

Reputation: 1103

yii send csv file charset

I work with yii-powered application. My goal is write controller action what exporting some data from mongodb to csv file using Yii 1.1: csvexport and CHttpRequest::sendFile

My code:

public function actionCatalogDataExport( $catalog_id )
{
    // prepare all needed variables here
    $data = ..., $headers = ..., $filename = ...     

    Yii::import('ext.csv.ECSVExport');
    $csv = new ECSVExport($data);
    $output = $csv->setHeaders($headers)->setDelimiter(',')->toCSV();
    Yii::app()->getRequest()->sendFile($filename, $output, "text/csv", true);
}

This script works properly, but if I open resulting file via Excel I see something like that:

enter image description here

There are some problems with file encoding... I opened notepad++ and changed encoding to UTF-8 without BOM, now file looks good (language: Ru):

enter image description here

Tested this fixes but no success results:

header('Content-type: text/csv; charset=UTF-8'); // no effect

Yii::app()->getRequest()->sendFile(
    $filename, 
    $output, 
    "text/csv; charset=UTF-8", // no effect
    true
);

How can I achieve this immediately after yii send file action?

Upvotes: 2

Views: 2907

Answers (2)

TotPeRo
TotPeRo

Reputation: 6781

Try to add the encode to begin of the csv file like this:

$encode = "\xEF\xBB\xBF"; // UTF-8 BOM
$content = $encode . $csv->toCSV();

//var_dump($content);
Yii::app()->getRequest()->sendFile($filename, $content, "text/csv; charset=UTF-8", false);

Upvotes: 1

itnelo
itnelo

Reputation: 1103

By default setup params, Excel for Windows opens csv files using windows-1251 encoding. If I need to make correct data values using this encoding I must use iconv

foreach( $data as $key => &$value ) {
    $value = iconv('UTF-8', 'windows-1251', $value);
}

// send file to user...
// ...and it works as I need.

Upvotes: 0

Related Questions