Writing to specific line number
Posted: Sun Apr 18, 2004 12:04 am
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.
A community of PHP developers offering assistance, advice, discussion, and friendship.
http://forums.devnetwork.net/
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);
}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);
?>