4

I'm trying to edit a file by line using SplFileObject(). I can choose the line of the file I want to edit. But how do I then write a $string to that line?

Here is my code to get the line:

<?php
$file = new SplFileObject('myfile.txt');
$file->seek(9999);     // Seek to line no. 10,000
echo $file->current(); // Print contents of that line
?>

How do I insert a string on that line?

Note, I don't want to overwrite the file, I simply want to insert a $string at a given line.

Charles
  • 50,943
  • 13
  • 104
  • 142
user3143218
  • 1,738
  • 5
  • 32
  • 48
  • Unfortunately, that's not how it works. Writing to files is at the scale of bytes, rather than lines. You'll have to write your new line (from where the old one started) but also have to re-write the rest of the file to make up for differences in line length (if the lines are different lengths). Depending on what you're *actually* trying to do by using this file, there might well be better alternatives. – salathe May 10 '14 at 14:32
  • Do you have any suggestions? – user3143218 May 10 '14 at 14:35
  • Depends. Are lines all of equal length? How against overwriting the file are you? Would you be averse to something like SQLite (row = line) instead of a text file? … – salathe May 10 '14 at 14:39
  • Actually it's another PHP file, the lines are varied in length. – user3143218 May 10 '14 at 14:44
  • 2
    is there some reason you cannot write a new file out that is a copy of the current file with the added string? – Ryan Vincent May 10 '14 at 15:23

1 Answers1

2

This isn't probably the best solution as it will read the whole file and store it in a string. But since there are no other answers you can use this as your last resource.

$ouput = '';
$file = new SplFileObject("your_file.xxx", 'r');
while (!$file->eof()) {
    $line = $file->fgets();
    if($line == 'your_condition'){
       $line = 'replace this line';
    }
    $output .= $line;
}
$file = null;

$file = new SplFileObject("your_file.xxx", 'w+');
$file->fwrite($output);
Jay Bhatt
  • 5,601
  • 5
  • 40
  • 62