fgetcsv在第一个项目上留下引号

时间:2018-09-19 11:55:00

标签: php quotes fgetcsv

我在读取包含用引号引起来的CSV文件时遇到问题。

我的CSV文件的第一行是标题,它们类似于以下内容:

"Header 1","Header 2","Header 3","Header 4","Header 5"

使用fgetcsv时,第一个标头保留周围的引号。

while (($row = fgetcsv($file, 6000, ',')) !== false)
{
    echo '<pre>';
    print_r($row);
    echo '</pre>';
    exit;
}

这会将以下内容输出到页面

Array
(
    [0] => "Header 1"
    [1] => Header 2
    [2] => Header 3
    [3] => Header 4
    [4] => Header 5
)

有人对如何确保第一个数组项目中不包含引号有任何建议吗?

谢谢

1 个答案:

答案 0 :(得分:0)

正如 Karsten Koop 的评论所说,这可能是由于 utf8 BOM 字符。而且由于 php 没有解决这个问题,你需要在打开 csv 文件进行阅读之前去掉那个字符。

即使用这样的函数 (more info):

public static function removeUtf8Bom($fileUri){
    $content = file_get_contents($fileUri);
    $content = str_replace("\xEF\xBB\xBF",'',$content);
    file_put_contents($fileUri,$content);
}