使用 fgetcsv 读取 CSV 文件时出现 UTF-8 问题 [英] UTF-8 problems while reading CSV file with fgetcsv

查看:26
本文介绍了使用 fgetcsv 读取 CSV 文件时出现 UTF-8 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试读取 CSV 并回显内容.但内容显示字符错误.

I try to read a CSV and echo the content. But the content displays the characters wrong.

Mäx Müstermänn -> Mäx Müstermänn

Mäx Müstermänn -> Mäx Müstermänn

CSV 文件的编码是没有 BOM 的 UTF-8(用 Notepad++ 检查).

Encoding of the CSV file is UTF-8 without BOM (checked with Notepad++).

这是 CSV 文件的内容:

This is the content of the CSV file:

"Mäx";"Müstermänn"

我的 PHP 脚本

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
$handle = fopen ("specialchars.csv","r");
echo '<table border="1"><tr><td>First name</td><td>Last name</td></tr><tr>';
while ($data = fgetcsv ($handle, 1000, ";")) {
        $num = count ($data);
        for ($c=0; $c < $num; $c++) {
            // output data
            echo "<td>$data[$c]</td>";
        }
        echo "</tr><tr>";
}
?>
</body>
</html>

我尝试使用 setlocale(LC_ALL, 'de_DE.utf8'); 作为建议 此处 没有成功.内容还是显示错误.

I tried to use setlocale(LC_ALL, 'de_DE.utf8'); as suggested here without success. The content is still wrong displayed.

我缺少什么?

一个 echo mb_detect_encoding($data[$c],'UTF-8'); 给我 UTF-8 UTF-8.

An echo mb_detect_encoding($data[$c],'UTF-8'); gives me UTF-8 UTF-8.

echo file_get_contents("specialchars.csv"); 给我 "Mäx";"Müstermänn".

print_r(str_getcsv(reset(explode("
", file_get_contents("specialchars.csv"))), ';'))

给我

Array ( [0] => Mäx [1] => Müstermänn )

什么意思?

推荐答案

现在我开始工作了(删除 header 命令后).我认为问题在于 php 文件的编码是 ISO-8859-1.我将它设置为没有 BOM 的 UTF-8.我以为我已经这样做了,但也许我做了一个额外的撤消.

Now I got it working (after removing the header command). I think the problem was that the encoding of the php file was in ISO-8859-1. I set it to UTF-8 without BOM. I thought I already have done that, but perhaps I made an additional undo.

此外,我为数据库使用了SET NAMES 'utf8'.现在在数据库中也是正确的.

Furthermore, I used SET NAMES 'utf8' for the database. Now it is also correct in the database.

这篇关于使用 fgetcsv 读取 CSV 文件时出现 UTF-8 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆