在mac上用excel转换成utf-8 csv文件

我是一个编码新手。 我有一个PHP文件,允许用户上传CSV文件。

我的问题是,如果该文件包含utf-8字符,如重音字母,使用Excel的Mac创build文件,我的代码将无法正常工作。 基本上它会忽略重音字符。

只有在使用Comma separated values选项保存文件时,才会出现该问题。

在所有其他情况下,如在Windows中创build文件或使用开放式办公或甚至在Mac上优秀,但将其保存为“窗口”文件不会造成任何问题。

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()打破了UTF-8字符

任何帮助或想法如何解决这个问题? 先谢谢你

这是安东尼发表的回应之后的新代码

 $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 

难道我做错了什么?

这是Excel的特定问题,在Mac上的Excel中更常见,UTF-8多字节字符未正确显示。 您可以使用其他电子表格查看器进行确认,例如Google表格。

解决方法是:

  1. 使用制表符( \t )而不是逗号作为分隔符(不要担心,它在技术上仍然是一个CSV)。

  2. 在编码为utf-8之后,将整个csvstring转换为UTF-16LE:

    mb_convert_encoding($csv_content, 'UTF-16LE', 'UTF-8');

  3. 以小端字节顺序标记(LE BOM)为前缀csvstring:

    $csv_content = chr(255) . chr(254) . $csv_content;

这应该做到这一点。

好的,谢谢安东尼,这里是解决问题的路线:

 $data = iconv('macintosh', 'UTF-8', $content); 

所以我的最终代码将如下所示:

 enter code here $content = file_get_contents(addslashes($file_name)); var_dump(mb_detect_encoding($content)); // need to do this for an issue specific to Excel and more common on Excel for Mac // using excel on mac if the file is saved as csv using the Comma separated values option we need to use iconv and not mb_convert_encoding // we use mb_detect_encoding because the content of such file returns a false value if(!mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true)){ //$data = mb_convert_encoding($content, 'UTF-8', mb_detect_encoding($content, 'UTF-8, ISO-8859-1', 'macintosh', true)); $data = iconv('macintosh', 'UTF-8', $content); } // deal with known encoding types else{ $data = mb_convert_encoding($content, 'UTF-8', mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true)); }