Read file in reverse order
Posted 13 April 2006 - 09:17 PM
Basically I just want to put the pointer to the end of the file and then read it in a reverse (bottom-up) order.
Thanks in advance!
Posted 13 April 2006 - 09:29 PM
- Use the file() function to read the file into an array.
- Use the array_reverse() function to reverse the array.
- Use a foreach loop to process each line.
<?php $input = file('input_file.txt'); $rev_input = array_reverse($input); foreach ($rev_input as $line) echo trim($line) . '<br>'; ?>
Posted 13 April 2006 - 09:49 PM
I'm working on a guestbook where latest entries are stored at the end of the file. And, of course, latest entries are displayed first.
Let's say I have 100 or 200 entries stored in the file, and I only need the last 10. It would be a waste of time and space to copy the whole file into an array and then choose 10 entries. What if there were 1000 or 10 000 entries in the file (I hope you get the idea).
I can also simply scan throw the whole file without copying anything until I come to the 10th last entry. From that point to the end I get my 10 latest entries.
It would be great if there was a function like fgetrs (like strpos/strrpos) for reading file backwards.
Posted 13 April 2006 - 11:19 PM
1. each entry is placed in its own file. the name of the file is the timestamp of when the file is created.
2. place the timestamp/filename into an "index" file
3. when accessing simply place the index file into an array and sort the array(even with 100's of entries still rather quick)
4. use an array function to "grab' the 10/20/30/ target timestamps and display them
wadda ya think?
[br][br]The truely intelligent people are not those who create the dots; rather they are they ones with the ability to connect the dots into a coherent picture
all the brothers were valiant!
Posted 14 April 2006 - 02:17 AM
Ok, I found a solution. Actually, it's not a solution, it's a workaround. I'm going to use txtSQL which is a pretty neat thing. It's somewhat a flat-file version of mysql.
But the problem of reading the file in reverse order is present and I will trying to find a way to do it. I really want to find the answer because this question arose a while ago but I never really had time to look into this problem.
0 user(s) are reading this topic
0 members, 0 guests, 0 anonymous users