PHP 抓取 txt 文件中的最后 15 行
感谢您花时间阅读本文,无论内容的质量如何,我都会感激每一个回复。 :)
使用 PHP,我尝试获取文本文档 (.txt) 的最后 15 行并将该数据存储到 php 变量中。我知道这是可能的,但是当我得到最后 15 行时,是否可以保留订单?例如:
文本文档:
A
B
C
当我从最后 15 个字符抓取文本文档时,我不希望回显结果如下:
C
B
A
感谢所有帮助,我期待您的回复;谢谢。 :) 如果我没有清楚地解释任何内容和/或您希望我更详细地解释,请回复。 :)
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
尝试使用 array_slice,它将返回数组的一部分。在本例中,您希望它返回数组的最后 15 行,因此:
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:
如果您不介意将整个文件加载到内存中:
如果文件太大而无法放入内存,您可以使用循环方法:
如果文件少于 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.
您可以使用带有负位置的 fseek 在文件中向后查找,同时计算换行符。
我太累了,无法编写可复制/粘贴的代码,但是 fseek 手册页的注释中有一些示例非常接近您想要的。
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.
如果文件不大于可用内存,您可以执行以下操作:
如果您有一个数百兆字节的文件:
If the file isn't bigger than available memory you can do this:
If you have a file that is hundreds of megabytes :
更长的数组解决方案:
array_slice(explode("\n",file_get_contents($file)),-15);
较短的数组解决方案:
array_slice(file($file),-15);
the longer array solution:
array_slice(explode("\n",file_get_contents($file)),-15);
the shorter array solution:
array_slice(file($file),-15);
此代码将打开文件,显示总行数,显示文件头并显示 $limit 中定义的文件的最后几行。
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.