我只想以csv格式导出数据并在excel中打开它。此方法将一行写入其中。
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ándo”
只有几个字母不正确(方法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)
结果是一样的。
答案 0 :(得分: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);