2015-09-07 93 views
0

我只想導出csv格式的數據並在Excel中打開它。這個方法寫入一行。Excel utf8編碼(物料清單不工作)

public function writeRow(array $row) 
    { 
     $str = $this->rowToStr($row); 
     $encodedStr = mb_convert_encoding($str, 'UTF-16LE', 'UTF-8'); 
     $ret = fwrite($this->_getFilePointer('w+'), $encodedStr); 

     /* According to http://php.net/fwrite the fwrite() function 
     should return false on error. However not writing the full 
     string (which may occur e.g. when disk is full) is not considered 
     as an error. Therefore both conditions are necessary. */ 
     if (($ret === false) || (($ret === 0) && (strlen($str) > 0))) { 
       throw new Exception("Cannot open file $this", 
       Exception::WRITE_ERROR, NULL, 'writeError'); 
     } 
    } 

然後我會嘗試寫一行。

$csvFile->writeRow(array(chr(0xEF) . chr(0xBB) . chr(0xBF))); 
$csvHeaders = array('ID', 'Email', 'Variabilní symbol', 'Jméno', 'Příjmení', 
'Stav', 'Zaregistrován', 'Zaregistrován do'); 
$csvFile->writeRow($csvHeaders); 

,其結果是:

ID, 「電子郵件」, 「Variabilní符號」, 「Jméno」, 「PYíjmení」, 「STAV」, 「Zaregistrován」, 「Zaregistrován做」

只有幾個字母是不正確的(方法mb_convert_encoding的伎倆)

我曾嘗試用傳統方式

// Open file pointer to standard output 
    $fp = fopen($filePath, 'w'); 

    // Add BOM to fix UTF-8 in Excel 
    fputs($fp, $bom = (chr(0xEF) . chr(0xBB) . chr(0xBF))); 
    fclose($fp) 

結果是一樣的。

回答

1

您提到的BOM是針對UTF-8的,但是您的數據是UTF-16LE。因此,你應該使用不同的BOM:

$bom = chr(0xFF) . chr(0xFE) 

或者在你的代碼:

$fp = fopen($filePath, 'w'); 
fputs($fp, chr(0xFF) . chr(0xFE)); 

// Add lines here... 

fclose($fp);