[php-src] Issue #8121: SplFileObject - Inconsistent behavior of seek and key with csv file

From: Date: Sun, 20 Feb 2022 05:18:15 +0000
Subject: [php-src] Issue #8121: SplFileObject - Inconsistent behavior of seek and key with csv file
Groups: php.bugs 
Request: Send a blank email to php-bugs+get-239900@lists.php.net to get a copy of this message
Issue: https://github.com/php/php-src/issues/8121
Author: Whip

### 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
<?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.

I am attaching the csv file I used as well.


### PHP Version

PHP 8.1.2

### Operating System

Windows 11, Xampp 3.3.0


Thread (1 message)

  • Whip
« previous php.bugs (#239900) next »