Search code examples
phpinsertline

How to insert string before last line?


I saw using fseek to insert string before last line this question, but this isn't solving my problem. I not use "?>" tag. Php version PHP 5.4

example line1
example line2
//i need insert here
lastline $eg};

My code is working but this is adding empty lines after all lines :

  $filename = 'example.php';   
  $arr = file($filename);
  if ($arr === false) {
      die('Error' . $filename);
    }
array_pop($arr);
file_put_contents($filename, implode(PHP_EOL, $arr));
/// I'm deleting last line here


$person = "my text here\n";
file_put_contents($filename, $person, FILE_APPEND);
$person = "andherelastline";
file_put_contents($filename, $person, FILE_APPEND);
//and then add again here

Solution

  • $file = "tmp/saf.txt";
    $fc = fopen($file, "r");
    while (!feof($fc)) {
        $buffer = fgets($fc, 4096);
        $lines[] = $buffer;
    }
    
    fclose($fc);
    
    //open same file and use "w" to clear file 
    $f = fopen($file, "w") or die("couldn't open $file");
    
    $lineCount = count($lines);
    //loop through array writing the lines until the secondlast
    for ($i = 0; $i < $lineCount- 1; $i++) {
        fwrite($f, $lines[$i]);
    }
    fwrite($f, 'Your insert string here'.PHP_EOL);
    
    //write the last line
    fwrite($f, $lines[$lineCount-1]);
    fclose($f);