如何将 FGETSCSV 与 CSV 文件一起使用,以使用 PHP 将文件解析为数组


how to use fgetscsv with a csv file to parse the file into an array using PHP

好的,所以我一直在试图让它工作几个小时,但无法弄清楚。我得到了一个格式为

item 1, item 1 stuff
item 2, item 2 stuff
item 3, item 3 stuff
item 4, item 4 stuff

我试图使用 fgetscsv 将其解析为数组。

$file = fopen('test.csv', 'r');
    while (($MyCSVArray = fgetcsv($file)) !== FALSE) {
    print_r($MyCSVArray);
}
fclose($file);

我真的宁愿将其解析为关联数组,以便我可以像这样索引它

MyCSVArray[item 1]

这将输出

item 1 stuff

但是我遇到的问题是,由于每个值后都没有逗号,它将项目 1 的东西与项目 2 分组,如下所示

MyCSVArray[0] = item 1
MyCSVArray[1] = item 1 stuff item 2
MyCSVArray[2] = item 2 stuff item 3

也许我不了解 csv 文件或 csv 功能,但我真的需要它以我想要的方式工作,并且不了解如何让它工作,并且即将把我的脸砸到键盘上。

只需像您一样读取数据,并根据需要将值设置为新的关联数组

$new_array = array()
$file = fopen('test.csv', 'r');
while (($MyCSVArray = fgetcsv($file)) !== FALSE) {
    $new_array[$MyCSVArray[0]] = $MyCSVArray[1];
}
fclose($file);
var_dump($new_array);

对于问题的第二部分,如果下一行中的项目与上一行中的项目分组,则文件中似乎没有正确的行尾字符。