Brah0um
Brah0um

Reputation: 345

PHP - SplFileObject write CSV in the first line

How can I write the following array in CSV format into the specific line of my file. I'm using the PHP LimitIterator to retrieve a part of my file.

$fields = ['value_1', 'value_2', 'value_3'];
$fileObject = new SplFileObject('my/file/path', 'r+');
$fileObject->setFlags(
    SplFileObject::READ_CSV |
    SplFileObject::SKIP_EMPTY |
    SplFileObject::READ_AHEAD |
    SplFileObject::DROP_NEW_LINE
);
$fileObject->setCsvControl($delimiter, $enclosure);
$iterator = new LimitIterator($fileObject, 5, 100); // Get file content starting at line 5

foreach ($iterator as $index => $row) {
    if (3 === $index) {
        // ...
        // My business logic
        // ...

        // I wanna write at line 8 but actually right at the content at line 9
        $fileObject->seek($iterator->getPosition() - 1); // Retrieve the right position
        $fileObject->fputcsv($fields, $delimiter, $enclosure); // Write of the line after the seek().
    }
}

Do anyone knows any method ? I'm really stuck :O

Upvotes: 0

Views: 605

Answers (0)

Related Questions