Writing to specific line number
Moderator: General Moderators
Writing to specific line number
Can someone please give me an example of how to write to a specific line number in a file so that it overwrites the line number in the process.
- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
Code: Select all
if(is_file($filename) && is_readable($filename) && is_writable($filename) && ($contents = file($filename))!==false))
{
if($contentsї$line-1] <= sizeof($contents))
{
$contentsї$line-1] = $newline;
}
file_put_contents($filename,$contents);
}whoops, that's php5 only.
It's still possible to do it with php4.. you just have to fopen(), fwrite(), fclose() on your own instead of file_put_contents()..
Also, you could use file() to read the file into an array, then replace the $array[number] of choise...
[Edit: Bad spelling and commented code better. --JAM]
Code: Select all
<?php
$array = file('test.txt');
// note, array starts at 0...
$array[3] = 'Wohoooo'; // ...so line 4 is actually replaced
$handle = fopen('test.txt', 'w+'); // open file, truncate to 0 lenght
foreach ($array as $key => $val) {
fwrite($handle, $val."\n"); // adding newlines using \n
}
fclose($handle);
?>
Last edited by JAM on Sun Apr 18, 2004 12:49 pm, edited 1 time in total.