gpt4 book ai didi

php - fgetcsv() 错误地将双引号添加到第一行的第一个元素

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:44:17 24 4
gpt4 key购买 nike

我对 fgtcsv() 有一个很好奇的问题。看这段代码

  $csv_check = fopen(CSV_DIR.$this->db_table.".csv","r");
$data = fgetcsv($csv_check, 1000, $this->fields_terminated_by);
fclose($csv_check);

A print_r($data) 输出以下内容:

array (
0 => '"program_id"',
1 => 'program_name',
2 => 'program_logo',
)

奇怪的是,$data[0] 在这里用双引号引起来...此 CSV 文件中的原始行如下所示:

"program_id";"program_name";"program_logo"

我完全不明白...用 strlen($data[0]) 计算 $data[0] 的字符返回 15,即使引用错误,它也必须是 12 个字符...我'我很震惊...!

有什么想法吗?!?

最佳答案

来自 PHP.net notes :

When a BOM character is suppled, fgetscsv may appear to wrap the first element in "double quotation marks". The simplest way to ignore it is to progress the file pointer to the 4th byte before using fgetcsv.

<?php

// BOM as a string for comparison.
$bom = "\xef\xbb\xbf";

// Read file from beginning.
$fp = fopen($path, 'r');

// Progress file pointer and get first 3 characters to compare to the BOM string.
if (fgets($fp, 4) !== $bom) {
// BOM not found - rewind pointer to start of file.
rewind($fp);
}

// Read CSV into an array.
$lines = [];
while (!feof($fp) && ($line = fgetcsv($fp)) !== false) {
$lines[] = $line;
}

关于php - fgetcsv() 错误地将双引号添加到第一行的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29828508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com