Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Get last line of a ".txt"

Status
Not open for further replies.

JEG

Technical User
Jan 4, 2002
2
US
How can I figure out how many lines there is in a txt file, and then use the trim function to get it into an variable?
 
you can read the file data into an array and then access the last element in that array. i'm using explode on new lines (\n) to put each line in the array. example:
Code:
$filename = "data.txt";
$fp = fopen($filename, "r");
$file_data = explode("\n",fread($fp, filesize($filename)));
fclose($fp);

echo $file_data[count($file_data)-1];[/b]

this will print the last line in the file.
Code:
count($file_data)
will hold the number of lines in the file.

hope this helps (-:
 
instead of using
$fp=fopen("data.txt")
Code:
$file_data=explode("\n", fread(...))

u can also use:
Code:
$file_data=file("data.txt");
and so on...

the only disadvantage is that the "\n" character still remains. But that could be usefull sometimes:

Code:
echo nl2br($file_data[count($file_data)-1]);

so you'll have a <br> tag after the lines...

just see which solution is better
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top