Forum Moderators: coopster

Message Too Old, No Replies

how to delete first line of a text file

         

laura2k

3:39 pm on Jun 20, 2004 (gmt 0)



hi,

can anyone please tell me how i can open a data.txt file and remove the first line and then save it.

thanx

jatar_k

4:07 pm on Jun 20, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



you could

fopen
file [ca3.php.net]
remove the first element from the resulting array
fwrite (using a loop or implode first then write)
fclose

laura2k

12:14 pm on Jun 23, 2004 (gmt 0)



actually i need to open the file and then remove the first three lines and then save the file. how can this be done? i am a complete novice so would appreciate some detailed explanation :)

Netizen

1:06 pm on Jun 23, 2004 (gmt 0)

10+ Year Member



Something like this should work:

$arrayOfLines=file [php.net]('yourfilename');

$linesIWant=array_slice [php.net]($arrayOfLines,3);

$fileContents=implode("\n",$linesIWant);

$fp=fopen('newfile','w+');
fwrite($fp,$fileContents);
fclose($fp);

cached

8:30 pm on Jul 22, 2004 (gmt 0)

10+ Year Member




function delxlines($txtfile, $numlines)
{
if (file_exists("temp.txt"))
{
unlink("temp.txt");
}

$arrayz = file("$txtfile");
$tempWrite = fopen("temp.txt", "w");
for ($i = $numlines; $i < count($arrayz); $i++)
{
fputs($tempWrite, "$arrayz[$i]");
}
fclose($tempWrite);
copy("temp.txt", "$txtfile");
unlink("temp.txt");
}


paste that into the top of your php code. Then if you want to delete the first 3 lines of bob.txt for example, you do delxlines("bob.txt", 3)