S
S
Sergey2016-02-05 09:53:30
PHP
Sergey, 2016-02-05 09:53:30

How to fix encoding bug when exporting to CSV?

public function actionTest(){
    $content = '"Привет мир";"test"';
    $this->stream($content, 'contacts.cvs');
}

private function stream($content, $name){
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.$name);
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: '.strlen($content));
    echo $content;
    exit();
}

The file is downloaded, when you open it in excel, krakozyabry appears instead of Russian characters. If you open the file in Notepad++ and set "utf-8 without BOM", then everything is fine.
Remove BOM function doesn't work:
function remove_utf8_bom($text){
    $bom = pack('H*','EFBBBF');
    $text = preg_replace("/^$bom/", '', $text);
    return $text;
}

The question is how to make it so that in excel the file opens in the correct encoding?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Kirill Arutyunov, 2016-02-05
@arutyunov

This is a problem in Excel itself - google how to properly open Excel files in UTF-8 (through data import, in my opinion).
artkiev.com/blog/excel-import-csv-utf-8.htm

S
Sergey, 2016-02-05
@frost18

I found a solution, I don’t know how correct it is, added BOM.

static function addBOM($text){
    return chr(239).chr(187).chr(191).$text;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question