0

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

Brah0um
  • 315
  • 2
  • 15
  • What if the new data on a line is longer than the current data? You may be better off rewriting the whole file with the new data. – Nigel Ren Sep 26 '19 at 14:43
  • I'm using the LimitIterator to get a part of my file content. I wanna update content this part at a specific line only – Brah0um Sep 26 '19 at 14:57

0 Answers0