使用PHP在巨大的文件中获取一行 [英] Getting one line in a huge file with PHP

查看:123
本文介绍了使用PHP在巨大的文件中获取一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在3 gig文本文件中获取特定行.这些行由\ n分隔.而且我需要能够按需获得任何生产线.

How can i get a particular line in a 3 gig text file. The lines are delimited by \n. And i need to be able to get any line on demand.

这怎么办?只需要返回一行.而且我不想使用任何系统调用.

How can this be done? Only one line need be returned. And i would not like to use any system calls.

注意:关于如何在bash中执行此操作,其他地方存在相同的问题.我想将其与PHP等效项进行比较.

Note: There is the same question elsewhere regarding how to do this in bash. I would like to compare it with the PHP equiv.

更新:每行在整个过程中的长度都是相同的.

Update: Each line is the same length the whole way thru.

推荐答案

如果不保留文件的某种索引,则需要读取所有索引,直到遇到x个\ n字符为止.我看到nickf刚刚发布了一些方法,所以我不再重复.

Without keeping some sort of index to the file, you would need to read all of it until you've encountered x number of \n characters. I see that nickf has just posted some way of doing that, so I won't repeat it.

要以有效的方式重复执行此操作,您将需要构建索引.为某些(或所有)行号存储一些已知的文件位置,然后您可以使用 fseek .

To do this repeatedly in an efficient manner, you will need to build an index. Store some known file positions for certain (or all) line numbers once, which you can then use to seek to the right location using fseek.

如果每行长度相同,则不需要索引.

if each line is the same length, you do not need the index.

$myfile = fopen($fileName, "r");
fseek($myfile, $lineLength * $lineNumber);
$line = fgets($myfile);
fclose($myfile);

在此示例中,行号为0,因此您可能需要先减去一个.行长包含\n字符.

Line number is 0 based in this example, so you may need to subtract one first. The line length includes the \n character.

这篇关于使用PHP在巨大的文件中获取一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆