在php(yii1.1 framework)中处理csv文件时,爱尔兰口音变成了有线字符

pn9klfpd  于 2022-11-09  发布在  PHP
关注(0)|答案(1)|浏览(142)

我知道有很多类似的问题已经在这个社区问,但不幸的是没有什么会为我工作。
我有一个CSV表,我需要在我们的系统中导入。表正在导入没有任何问题的Linux(创建与自由办公室表),甚至与爱尔兰字符。
但主要的问题开始在Windows和iOS环境与excel(MS-excel)的字符编码得到改变.和爱尔兰字符很少像
,和许多其他符号被改变成不同的符号。

P.S:如果我们在iOS中通过Numbers创建CSV,CSV工作正常。

下面是我阅读CSV表单的php方法。

$path = CUploadedFile::getInstance($model, 'absence_data_file'); // Get the instance of selected file
$target = ['First Name', 'Last Name', 'Class', 'Year', 'From']; // Valid Header

public static function readCSV($path, $target) {
        $updated_header = array();
        $data = array();
        if ($path->type == 'text/csv' || $path->type == 'application/vnd.ms-excel' || $path->type == 'text/plain' || $path->type == 'text/tsv') {
            $fp = fopen($path->tempName, 'r');
            $encoding_type = mb_detect_encoding(file_get_contents($path->tempName));

            if ($fp !== FALSE) {
                $header = fgetcsv($fp);
                foreach ($header as $h) {
                    $updated_header[] = $h;
                }
                $updated_header = array_map( 'trim', array_values($updated_header));
                if (array_diff($target, $updated_header)) {
                    $errormessage = 'Invalid header format.';
                    return $errormessage;
                } else {
                    while ($ar = fgetcsv($fp)) {
                        $data[] = array_combine($updated_header, $ar);
                    }
                    $data['file_encoding'] = $encoding_type;
                    return $data;
                }
            }
        } else {
            $errormessage = "Invalid File type, You can import CSV files only";
            return $errormessage;
        }
    }

我正在导入的表(检查图片):

打印数据(第一条记录)

ukdjmx9f

ukdjmx9f1#

我不确定爱尔兰代码页,但如果它是西欧,如您在评论中提到的,我猜您的代码页将是ISO-8859-1或ISO-8859-14,您的代码行应该是:

$encoding_type = mb_detect_encoding(file_get_contents($path->tempName), 'ISO-8859-1', true);

或者只是简单地跟随,因为您确定其编码是“ISO-8859-1”

$encoding_type = 'ISO-8859-1'

mb_detect_encoding中的第二个和第三个参数告诉函数严格尝试并使用ISO-8859-1进行编码。如果要同时尝试其他代码页,可以为第二个参数提供逗号分隔的代码页列表,例如UTF-8, ISO-8859-1
请注意,您需要调用mb_convert_encoding以实际获取所需编码的文件,因此以下代码将严格尝试从ISO-8859-1解码为UTF-8

$UTF8_text =  mb_convert_encoding($content, 'UTF-8', 'ISO-8859-1');

如果你坚持使用fgetcsv,可以看一下(mb_internal_encoding)[https://www.php.net/manual/en/function.mb-internal-encoding.php],它会设置默认编码。

相关问题