将 csv 文件处理为 UTF-8

Processing csv file as UTF-8

试图找出如何处理具有 UTF 编码的 csv 文件。尝试了多种方法,例如添加此 utf8_encode() 并在 header:

中添加此
header('Content-Type: text/html; charset=UTF-8');

但似乎没有任何效果。

密码是:

<?php
include 'head.php';
$csv = array_map("str_getcsv", file("translations/dk.csv"));
foreach ($csv as $line){
     $translate["dk"][ $line[0] ] = $line[1];
}if ($line[1] != NULL){
    $line[0] = $line[1];
}
echo $line[0];
fclose($csv);
?>

如何使用 UTF-8 编码回显输出?

当你在浏览器中显示它时,你应该使用有效的 html 并将元字符集也设置为 utf8:

<?php
include 'head.php';
?>
<!DOCTYPE html>
<html lang="dk">
<head>
    <meta charset="utf-8"/>
</head>
<body>
<?php

$csv = array_map("str_getcsv", file("translations/dk.csv"));
foreach ($csv as $line){
     $translate["dk"][ $line[0] ] = $line[1];
}if ($line[1] != NULL){
    $line[0] = $line[1];
}
echo $line[0];
fclose($csv);
?>
</body>
</html>

或者使用 text/plain 而不是 text/html 可以帮助:

header('Content-Type: text/plain; charset=UTF-8');

希望对您有所帮助。

根据您的描述,该文件似乎不是 UTF-8 格式,可能是 ISO-8859-1,但您试图显示为 UTF-8,因此您为什么看到奇怪的块状符号。

您有两个选择,您可以使用以下方法将文件条目转换为 UTF-8:

foreach ($csv as $line)
    $translate["dk"][$line[0]] = utf8_encode($line[1]);

或者向浏览器声明文件真实编码,以便正确显示:

header('Content-Type: text/html; charset=ISO-8859-1');

由于 W3C 推荐 UTF-8 作为 Web 的默认编码,因此应该首选第一个选项。

或者,您可以使用您最喜欢的文本编辑器将整个文件转换为 UTF-8 格式并以这种方式保存,这样您就不必每次都将其转换为 UTF-8 格式。