SplFileObject无法正确读取CSV

时间:2016-10-07 06:57:15

标签: php csv splfileobject

因此,我必须阅读多个CSV文件,合并其标题(通过删除重复项)并将值放入最终(合并)的CSV文件中。我想第一次使用SplFileObject。我开始阅读文件。以下是详细信息

file1.csv

"A","B","C","D
1,2,3,4

merge.csv

$file = new SplFileObject('file1.csv');
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $row) {
    print_r($row);
}

输出:

Array
(
    [0] => A
    [1] => B
    [2] => C
    [3] => D
1,2,3,4
)

为什么它没有为下一行创建另一个数组?

1 个答案:

答案 0 :(得分:1)

试试这个,将数据存储在数组中并打印出来。

$file = new SplFileObject('file1.csv');
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $row) {
   $new_array[] = $row;
}
print_r($new_array);

<强>输出

Array
(
    [0] => A
    [1] => B
    [2] => C
    [3] => D
    [4] => 1
    [5] => 2
    [6] => 3
    [7] => 4
)

试试这个,

$file = fopen('file1.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
  //$line is an array of the csv elements
  print_r($line);
}
fclose($file);