-
Notifications
You must be signed in to change notification settings - Fork 8k
Closed
Description
Description
In the code below, I'm opening a csv file, seeking to each line and trying to get the contents. $file->current() returns the correct line everytime but $file->key() returns 0 and then 1 for each line. This only happens when with READ_AHEAD and READ_CSV flags are used.
Note that o() is just a wrapper for echo and print_r.
The following code:
<?php
$file = new SplFileObject('import2.csv', 'r');
$file->setFlags(SplFileObject::READ_AHEAD | SplFileObject::READ_CSV | SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE);
$file->seek(0);
o($file->key());
o($file->current());
$file->seek(1);
o($file->key());
o($file->current());
$file->seek(2);
o($file->key());
o($file->current());
$file->seek(3);
o($file->key());
o($file->current());Resulted in this output:
0
id,status,on_sale,brand,name,link,meta_title,meta_desc,description
1
1,2,15,Samsung,M21,samsung-m21,Samsung M21,Samsung M21,Samsung M21
1
2,2,15,Samsung,M32,samsung-m32,Samsung M32,Samsung M32,Samsung M32
1
3,2,15,Samsung,M21,samsung-m21,Samsung M21,Samsung M21,Samsung M21
But I expected this output instead:
0
id,status,on_sale,brand,name,link,meta_title,meta_desc,description
1
1,2,15,Samsung,M21,samsung-m21,Samsung M21,Samsung M21,Samsung M21
2
2,2,15,Samsung,M32,samsung-m32,Samsung M32,Samsung M32,Samsung M32
3
3,2,15,Samsung,M21,samsung-m21,Samsung M21,Samsung M21,Samsung M21
If I remove READ_CSV flag, the line numbers I get are
0
2
3
4
Finally, If I remove READ_AHEAD as well, I get the expected output.
Looping through
When not using seek, everything works fine.
$file = new SplFileObject('import2.csv', 'r');
$file->setFlags(SplFileObject::READ_AHEAD | SplFileObject::READ_CSV | SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE);
foreach ($file as $row) {
o($file->key());
}
Outputs
0
1
2
3
I am attaching the csv file I used as well.
PHP Version
PHP 8.1.2
Operating System
Windows 11, Xampp 3.3.0