Thank you for taking the time to read this and I will appreciate every single response no mater the quality of content. :)
Using PHP, I'm trying to get the last 15 lines of a text document (.txt) and store that data into a php variable. I understand that this is possible, however when I do get the last 15 lines, is it possible to retain the order? For example:
text document:
A
B
C
When I grab the text document from the last 15 characters, I don't want the echo to end up like:
C
B
A
All assistance is appreciated and I look forward to your replies; thank you. :) If I didn't explain anything clearly and/or you'd like me to explain in more detail, please reply. :)
Thank you.
You can use fseek with a negative position to seek backwards through the file, counting newlines as you go.
I'm too tired to write up copy/past-able code, but there are some examples in the comments to the manual page for fseek that are very close to what you want.
the longer array solution:
array_slice(explode("\n",file_get_contents($file)),-15);
the shorter array solution:
array_slice(file($file),-15);
If you don't mind loading the entire file into memory:
If the file is too large to fit into memory you can use a circular method:
This method will also work if the file has less than 15 lines- returning an array with however many lines are in the file.
This code will open the file, show the total lines, show the header of file and show the last lines of file defined in $limit.
Try using array_slice, which will return a part of an array. In this case you want it to return the last 15 lines of the array, so:
If the file isn't bigger than available memory you can do this:
If you have a file that is hundreds of megabytes :