【发布时间】:2015-03-28 04:39:13
【问题描述】:
我是一个编码新手。 我有一个允许用户上传 csv 文件的 php 文件。
我的问题是,当使用 excel for mac 创建文件时,如果文件包含重音字母等 utf-8 字符,我的代码将无法正常工作。基本上它会忽略重音字符。
仅当使用Comma separated values 选项保存文件时才会出现此问题。
在所有其他情况下,例如在 windows 中创建文件或使用 open office 甚至是 mac 上的 excel,但将它们保存为“windows”文件不会导致任何问题。
mb_detect_encoding 为导致问题的文件返回 false。
代码如下:
// say there is the word Nestlé in the file
$content = file_get_contents(addslashes($file_name));
var_dump(mb_detect_encoding($content)); // print false
$data = mb_convert_encoding($content, 'UTF-8', mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true));
//$data = utf8_encode($content); //doesn't work
var_dump($data); // print Nestl
ini_set('auto_detect_line_endings',TRUE);
// more code here we don't need at the moment
这个问题给了我一些暗示:file_get_contents() Breaks Up UTF-8 Characters
关于如何解决这个问题的任何帮助或想法?提前谢谢你
这是 Anthony 发布响应后的新代码
$content = file_get_contents(addslashes($file_name));
// i have no control on how the file is generated so i need to to the replace in the code
$content = str_replace(",", "\t", $content);
var_dump($content);
$data = mb_convert_encoding($content, 'UTF-8', mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true));
$data = mb_convert_encoding($data, 'UTF-16LE', 'UTF-8');
$data = chr(255) . chr(254) . $data;
var_dump($data); // this still print funny characters not the accented letter
我做错了吗?
【问题讨论】:
-
这是 osx 上 excel 的已知问题,缺少对 csv 文件的 Unicode 支持。有一个解决方法,我会发布一些。你没有做错,它是 excel
-
@Anthony 这对我来说是个不错的生日礼物 :)