Reading .txt lines

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ManiZach
Forum Newbie
Posts: 3
Joined: Fri Jul 16, 2010 4:20 pm

Reading .txt lines

Post by ManiZach »

Hi! I need help with creating a small snippet... I want a code that reads the 5 last lines of a txt file (Reading the newest items added only.) How can this be done?

Thanks!
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Reading .txt lines

Post by AbraCadaver »

Probably a better way, but I'm off to bed:

Code: Select all

$lines = file('/path/to/file.txt');
for($i=count($lines)-5; $i<count($lines); $i++) {
  echo $lines[$i];
}
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Reading .txt lines

Post by requinix »

I'd use array_slice.

Code: Select all

foreach (array_slice($lines, -5) as $line) {
Post Reply