Reputation: 35
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
Upvotes: 1
Views: 2299
Reputation: 47883
Until you need to implement file locking or contend with enormous file sizes, then just get the content, use a regular expression to find the new line character before the last line, inject the new line, then save the file.
$filename = 'example.txt';
$new = 'your new text';
file_put_contents(
$filename,
preg_replace(
'/\R(?=.+$)/', // match last occurring newline sequence followed by: one or more non-newline characters before the end of the string
'\0' . $new . '\0', // inject the new text with same newline sequence already used in file
file_get_contents($filename)
)
);
Upvotes: 0
Reputation: 1
fseek solution in case your files are HUGE
$f = fopen('filename', 'r+');
fseek($f, -1, SEEK_END);
// skip spaces and empty lines at end of the file
while (in_array(fread($f, 1), [" ", "\n", "\r", "\t", "\v", "\0"], true)) {
fseek($f, -2, SEEK_CUR);
}
// move position indicator right before last content line
$lineLenth = 0;
while (fread($f, 1) !== PHP_EOL) {
fseek($f, -2, SEEK_CUR);
$lineLenth++;
}
// backup old content
$lastLine = fgets($f);
// move position indicator again since fgets() moved it back to the line end
fseek($f, -$lineLenth - 1, SEEK_CUR);
$newContent = 'Data to be insert' . PHP_EOL . $lastLine;
fwrite($f, $newContent);
fclose($f);
tested with php 8.1
Upvotes: 0
Reputation: 24555
$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);
Upvotes: 5