我有数据.csv文件,必须上传到服务器,解析....
此文件可以有不同的编码。我必须检测到它并转换为 utf8。
此时 php 函数mb_detect_encoding总是返回 utf8。我试过了:
<?php
mb_detect_encoding(file_get_contents($_FILES["csv_uploadfile"]["tmp_name"]));
或
<?php
mb_detect_encoding(file_get_contents($saved_file_path));
mb_detect_encoding返回 utf8。
如果我使用 bash 命令
$ file -bi csv_import_1378376486.csv |awk -F "=" '{print $2}'
它重新定义了ISO-8859-1
所以当我尝试时
iconv --from-code=iso-8859-1 --to-code=utf-8 csv_import_1378382527.csv
它不可读。
真正的编码是cp1251,我无法检测到它。谁能帮我解决这个问题?
正如有人在这里的 PHP 文档中注意到的那样:
如果尝试使用 mb_detect_encoding() 来检测字符串是否 有效的 UTF-8,使用严格模式,否则毫无价值。
因此,您应该在检测编码时尝试使用 true
参数:
mb_detect_encoding($str, mb_detect_order(), TRUE);
如果可以预测一些可能的编码,则可以列出它们,而不是使用 mb_detect_order()
。