相关疑难解决方法(0)

使用fgetcsv读取CSV文件时出现UTF-8问题

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

MäxMüstermänn - >MäxMüstermänn

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

这是CSV文件的内容:

"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>
Run Code Online (Sandbox Code Playgroud)

我尝试setlocale(LC_ALL, 'de_DE.utf8');按照这里的建议使用但没有成功.内容仍然显示错误.

我错过了什么?

编辑:

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

php csv utf-8 fgetcsv

31
推荐指数
6
解决办法
10万
查看次数

fgetcsv()在行的开头忽略特殊字符!

我有一个简单的脚本,它接受一个CSV文件并将每一行读入一个数组.然后,我循环遍历第一行的每一列(在我的情况下,它包含调查问题)并打印出来.调查是法语的,每当问题的第一个字符是特殊字符(é,ê,ç等)时,fgetcsv就会省略它.

值的中间的特殊字符仅在它们是第一个字符时才受影响.

我试着调试这个,但我很困惑.我做了一个var_dump与文件的内容,字符肯定在那里:

var_dump(utf8_encode(file_get_contents($_FILES['csv_file']['tmp_name'])));
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

if(file_exists($_FILES['csv_file']['tmp_name']) && $csv = fopen($_FILES['csv_file']['tmp_name'], "r"))
    {
        $csv_arr = array();

        //Populate an array with all the cells of the CSV file
        while(!feof($csv))
        {
            $csv_arr[] = fgetcsv($csv);
        }

        //Close the file, no longer needed
        fclose($csv);

        // This should cycle through the cells of the first row (questions)
        foreach($csv_arr[0] as $question)
        {
            echo utf8_encode($question) . "<br />";
        }

    }
Run Code Online (Sandbox Code Playgroud)

php csv fgetcsv

11
推荐指数
2
解决办法
1万
查看次数

标签 统计

csv ×2

fgetcsv ×2

php ×2

utf-8 ×1