homepage Welcome to WebmasterWorld Guest from 50.19.144.243
register, free tools, login, search, subscribe, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
Remove last line in a file PHP/Store all lines except the last one
ktsirig




msg:3996766
 11:33 pm on Sep 27, 2009 (gmt 0)

Hello all! Is there a way to remove the last line in a text file? Or, alternatively, is there a way to read a text file until the penultimate line of the file?
That is, if you have a file like:

AAAA
BBBB
CCCC
DDDD
#*$!#*$!XX

read all lines except the last one? In the previous example I need to hold only AAAA, BBBB , CCCC and DDDD.
Thank you!

 

rocknbil




msg:3996796
 1:30 am on Sep 28, 2009 (gmt 0)

There may be a function for this, but I'd just store the lines in an array and use array_pop to remove the last item of the array, then overwrite the file.

array_shift [us3.php.net] removes the first item, array_pop [us3.php.net] the last, array_splice [us3.php.net] to remove items within the array.

A side note, all these return the removed items, so if you want to do anything with them, you can.

$removed = array_pop($line_array);

andrewsmd




msg:3997329
 9:55 pm on Sep 28, 2009 (gmt 0)

I didn't test this but I'm pretty sure it's close. I used to write a lot of text files
//the path of your file
$fileName = "temp.txt";

//all of the lines
$fileArray = file($fileName);
array_pop($fileArray);

//open the file for overwriting
$handle = fopen($fileName, "w");

//now write all of the lines except the last one
//that was removed from the array
foreach($fileArray as $i){

//if this doesn't work print some error
if(!(fwrite($handle, $i."\n"))){

echo("there was some error in writing the line $i");

}//if !(fwrite)
}
fclose($handle);

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About
© Webmaster World 1996-2014 all rights reserved