need a function to write the last 100 lines log reverse

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
User avatar
susrisha
Forum Contributor
Posts: 439
Joined: Thu Aug 07, 2008 11:43 pm
Location: Hyderabad India

need a function to write the last 100 lines log reverse

Post by susrisha »

Hello all.
I have a log file that keeps on updating due to one of the programs i wrote. The issue is that i want to read the last 100 lines of log file in reverse order. Found some function in http://in.php.net/manual/en/function.fseek.php
This isnt helping. Here is my requirement in detail:

Input log file has :
Line1
Line2
Line3
Line4
LastLine
===end of input===

Now i need an output as

LastLine
Line4
Line3
==== if given the number of lines from end of file as 3===

Can someone suggest me for writing this code. I am low on knowledge about the functions to be used.
Please guide me.
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: need a function to write the last 100 lines log reverse

Post by Eran »

You can read the file into an array and reverse the array - easy to do but this requires loading the entire file into memory, which could run you out of memory.

I use the following which will work on linux only -

Code: Select all

 
$file = popen("tac " . $file ,'r'); //Opens the file from the end
while ($line = fgets($file)) {
       //do what you want with each line
}
 
someberry
Forum Contributor
Posts: 172
Joined: Mon Apr 11, 2005 5:16 am

Re: need a function to write the last 100 lines log reverse

Post by someberry »

I would explode the data on new lines and then reverse the array.
User avatar
susrisha
Forum Contributor
Posts: 439
Joined: Thu Aug 07, 2008 11:43 pm
Location: Hyderabad India

Re: need a function to write the last 100 lines log reverse

Post by susrisha »

thanks alot for the code
Post Reply