PHP:从文件中读取特定行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5775452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:27:32  来源:igfitidea点击:

PHP: Read Specific Line From File

phpfileline

提问by Sang Froid

I'm trying to read a specific line from a text file using php. Here's the text file:

我正在尝试使用 php 从文本文件中读取特定行。这是文本文件:

foo  
foo2

How would I get the content of the second line using php? This returns the first line:

如何使用 php 获取第二行的内容?这将返回第一行:

<?php 
$myFile = "4-24-11.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
?>

..but I need the second.

..但我需要第二个。

Any help would be greatly appreciated

任何帮助将不胜感激

回答by

$myFile = "4-24-11.txt";
$lines = file($myFile);//file in to an array
echo $lines[1]; //line 2

file — Reads entire file into an array

file — 将整个文件读入一个数组

回答by nimmneun

omgI'm lacking 7 rep to make comments. This is @Raptor's & @Tomm's comment, since this question still shows up way high in google serps.

天哪,我缺少 7 位代表来发表评论。这是@Raptor 和@Tomm 的评论,因为这个问题在 google serps 中仍然出现得非常高。

He's exactly right. For small files file($file);is perfectly fine. For large files it's total overkill b/c php arrays eat memory like crazy.

他完全正确。对于小文件file($file);完全没问题。对于大文件来说,b/c php 数组完全是矫枉过正,像疯了一样吃内存。

I just ran a tiny test with a *.csv with a file size of ~67mb (1,000,000 lines):

我刚刚使用 *.csv 文件进行了一个小测试,文件大小约为 67mb(1,000,000 行):

$t = -microtime(1);
$file = '../data/1000k.csv';
$lines = file($file);
echo $lines[999999]
    ."\n".(memory_get_peak_usage(1)/1024/1024)
    ."\n".($t+microtime(1));
//227.5
//0.22701287269592
//Process finished with exit code 0

And since noone mentioned it yet, I gave the SplFileObjecta try, which I actually just recently discovered for myself.

由于还没有人提到它,我SplFileObject试了一下,实际上我最近才为自己发现。

$t = -microtime(1);
$file = '../data/1000k.csv';
$spl = new SplFileObject($file);
$spl->seek(999999);
echo $spl->current()
    ."\n".(memory_get_peak_usage(1)/1024/1024)
    ."\n".($t+microtime(1));
//0.5
//0.11500692367554
//Process finished with exit code 0

This was on my Win7 desktop so it's not representative for production environment, but still ... quite the difference.

这是在我的 Win7 桌面上,所以它不代表生产环境,但仍然......相当不同。

回答by alex

If you wanted to do it that way...

如果你想那样做...

$line = 0;

while (($buffer = fgets($fh)) !== FALSE) {
   if ($line == 1) {
       // This is the second line.
       break;
   }   
   $line++;
}

Alternatively, open it with file()and subscript the line with [1].

或者,用 将其打开并用file()下标该行[1]

回答by Phil

I would use the SplFileObject class...

我会使用 SplFileObject 类...

$file = new SplFileObject("filename");
if (!$file->eof()) {
     $file->seek($lineNumber);
     $contents = $file->current(); // $contents would hold the data from line x
}

回答by balanv

you can use the following to get all the lines in the file

您可以使用以下内容获取文件中的所有行

$handle = @fopen('test.txt', "r");

if ($handle) { 
   while (!feof($handle)) { 
       $lines[] = fgets($handle, 4096); 
   } 
   fclose($handle); 
} 


print_r($lines);

and $lines[1]for your second line

$lines[1]你的第二行

回答by Phoenix

$myFile = "4-21-11.txt";
$fh = fopen($myFile, 'r');
while(!feof($fh))
{
    $data[] = fgets($fh);  
    //Do whatever you want with the data in here
    //This feeds the file into an array line by line
}
fclose($fh);

回答by cantelope

This question is quite old by now, but for anyone dealing with very large files, here is a solution that does not involve reading every preceding line. This was also the only solution that worked in my case for a file with ~160 million lines.

这个问题现在已经很老了,但是对于处理非常大文件的任何人来说,这里有一个解决方案,它不涉及阅读每一行。这也是在我的案例中适用于大约 1.6 亿行文件的唯一解决方案。

<?php
function rand_line($fileName) {
    do{
        $fileSize=filesize($fileName);
        $fp = fopen($fileName, 'r');
        fseek($fp, rand(0, $fileSize));
        $data = fread($fp, 4096);  // assumes lines are < 4096 characters
        fclose($fp);
        $a = explode("\n",$data);
    }while(count($a)<2);
    return $a[1];
}

echo rand_line("file.txt");  // change file name
?>

It works by opening the file without reading anything, then moving the pointer instantly to a random position, reading up to 4096 characters from that point, then grabbing the first complete line from that data.

它的工作原理是打开文件而不读取任何内容,然后立即将指针移动到随机位置,从该点读取最多 4096 个字符,然后从该数据中获取第一行完整的行。

回答by mineroot

If you use PHP on Linux, you may try the following to read text for example between 74th and 159th lines:

如果您在 Linux 上使用 PHP,您可以尝试以下方法来阅读第 74 行和第 159 行之间的文本:

$text = shell_exec("sed -n '74,159p' path/to/file.log");

This solution is good if your file is large.

如果您的文件很大,则此解决方案很好。

回答by Rikesh

You have to loop the file till end of file.

你必须循环文件直到文件结束。

  while(!feof($file))
  {
     echo fgets($file). "<br />";
  }
  fclose($file);

回答by Sunit

Use stream_get_line: stream_get_line — Gets line from stream resource up to a given delimiter Source: http://php.net/manual/en/function.stream-get-line.php

使用 stream_get_line: stream_get_line — 从流资源获取行到给定的分隔符来源:http: //php.net/manual/en/function.stream-get-line.php