Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP:从文件中读取特定行_Php_File_Line - Fatal编程技术网

PHP:从文件中读取特定行

PHP:从文件中读取特定行,php,file,line,Php,File,Line,我正在尝试使用php从文本文件中读取特定行。 以下是文本文件: foo foo2 如何使用php获取第二行的内容? 这将返回第一行: <?php $myFile = "4-24-11.txt"; $fh = fopen($myFile, 'r'); $theData = fgets($fh); fclose($fh); echo $theData; ?> …但我需要第二个 任何帮助都将不胜感激 $myFile = "4-24-11.txt"; $lines = file

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

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

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

…但我需要第二个

任何帮助都将不胜感激

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

您必须循环文件直到文件结束

  while(!feof($file))
  {
     echo fgets($file). "<br />";
  }
  fclose($file);
while(!feof($file))
{
echo fgets($file)。“
”; } fclose($文件);
如果你想这样做

$line = 0;

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

或者,使用打开它,并使用
[1]

在该行下标。您可以使用以下命令获取文件中的所有行

$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);
$handle = @fopen('test.txt', "r");

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


print_r($lines);
还有,
$lines[1]
对于你的第二行

天哪,我缺少7位代表发表评论。这是@Raptor和@Tomm的评论,因为这个问题在google SERP中仍然显示得很高

他完全正确。对于小文件
文件($file)非常好。对于大文件来说,b/c php数组完全是杀伤力过大,它疯狂地消耗内存

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

既然还没有人提到它,我就尝试了一下
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

这是在我的Win7桌面上,所以它不代表生产环境,但仍然。。。差别很大。

使用stream\u get\u line:stream\u get\u line-从流资源中获取行,直到给定的分隔符
来源:

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

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

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

您可以尝试循环到所需的行,而不是EOF,然后每次都将变量重置到该行(而不是添加到该行)。在您的情况下,第二行是EOF。(在我下面的代码中,for循环可能更合适)

这样整个文件就不在内存中了;缺点是需要时间来浏览文件,直到达到您想要的点

<?php 
$myFile = "4-24-11.txt";
$fh = fopen($myFile, 'r');
$i = 0;
while ($i < 2)
 {
  $theData = fgets($fh);
  $i++
 }
fclose($fh);
echo $theData;
?>

我喜欢,但如果您的文件不够大,您可以尝试另一种解决方案

$file = __FILE__; // Let's take the current file just as an example.

$start_line = __LINE__ -1; // The same with the line what we look for. Take the line number where $line variable is declared as the start.

$lines_to_display = 5; // The number of lines to display. Displays only the $start_line if set to 1. If $lines_to_display argument is omitted displays all lines starting from the $start_line.

echo implode('', array_slice(file($file), $start_line, lines_to_display));

我将使用SplFileObject类

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

这个问题现在已经很老了,但对于任何处理超大文件的人来说,这里有一个解决方案,它不需要读取前面的每一行。这也是在我的案例中,对于一个大约有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
?>


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

我搜索了一种单行解决方案来读取文件中的特定行。 以下是我的解决方案:


echo文件('dayInt.txt')[1]

注意:应该是
$lines[1]
谢谢!这正是我需要的!另外,谢谢你这么快的回答。如果文件太大,这个解决方案会很慢并且占用很多内存。但是,40+以上的投票?我想说这还不算太糟;-)将整个文件读入内存只是为了得到第二行?我认为在某些情况下,这会导致灾难(见Raptor的评论)。因此,基本上,将其放入一个数组中,然后取出第二项。我懂了。谢谢。@Sang第一个解决方案刚刚给出,以适应您的代码现在的状态。啊。我懂了。谢谢你的回答。:)顺便说一下,如果您可能正在使用任何大文件,那么在实践中不建议将整个文件馈送到数组中,例如使用
file()
file\u get\u contents()
。对于小文件,它工作得很好。谢谢兄弟!我很感激你的回答。对于一个这么晚才回答这个问题的人来说,这是一个很好的回答,而且很有帮助+1请记住,
SplFileObject
会锁定文件。因此,当不再需要类时,请将其设置为null(例如,
$spl=null;
),或者您将被拒绝对该文件执行其他一些操作—删除、重命名、访问类之外的内容,等等。#sallet#revoutional awesome method:)而如果您知道该解决方案将部署在何处,则此解决方案可以工作,对于您不了解目标系统的情况,这不是最佳选择。
<?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
?>