0

Using the fgets() function (or any other way) in PHP is there a way to read the LAST line of a file then work backwards? What I am doing: (as per request) I am appending to a .txt file lines from an input (don't worry about that) and of course append adds to the END of a file so I need to display the contents of a file with one line being one entry to be displayed
So if the contents of the file are:
Hello, World!
Foo likes Bar!
then it needs to display as
1. Foo likes Bar!
2. Hello, World!

Grace B
  • 1,386
  • 11
  • 30
  • there is no such function. and there is no way to read by lines backwards using fgets. you can read a file by chunks. But you will do yourself a HUGE favor by telling the whole story - why do you need that and what lead you to this task. There is probably a trivial solution already – Your Common Sense Jan 21 '11 at 08:38
  • possible duplicate of [Read a file backwards line by line using fseek](http://stackoverflow.com/questions/3234580/read-a-file-backwards-line-by-line-using-fseek) – Gordon Jan 21 '11 at 08:52

2 Answers2

2

As far as I know PHP does not know the gets() function. But..

If you use 'file()' and inverse the array you can work it through from bottom to top. That should do the trick for you!

Sander
  • 1,244
  • 1
  • 12
  • 24
0

If it is a really big file, it might be better to use the following...

exec("tail -1 input_file > output_file") ;
$string = file_get_contents("output_file") ;
unlink("output_file") ;

This is based on UNIX/Linux system commands, but I'm sure Windows has a command similar to tail.