問題描述
我嘗試讀取 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 問題的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!