PHP: Read Specific Line From File

PhpFileLine

Php Problem Overview


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

foo  
foo2

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

<?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

Php Solutions


Solution 1 - Php

$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

Solution 2 - Php

omg I'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.

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.

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

$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 SplFileObject a try, which I actually just recently discovered for myself.

$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.

Solution 3 - Php

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].

Solution 4 - Php

I would use the SplFileObject class...

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

Solution 5 - Php

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

Solution 6 - Php

$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);

Solution 7 - Php

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.

<?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.

Solution 8 - Php

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

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

This solution is good if your file is large.

Solution 9 - Php

You have to loop the file till end of file.

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

Solution 10 - Php

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

Solution 11 - Php

You could try looping until the line you want, not the EOF, and resetting the variable to the line each time (not adding to it). In your case, the 2nd line is the EOF. (A for loop is probably more appropriate in my code below).

This way the entire file is not in the memory; the drawback is it takes time to go through the file up to the point you want.

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

Solution 12 - Php

I like daggett answer but there is another solution you can get try if your file is not big enough.

$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));

Solution 13 - Php

I searched for a one line solution to read specific line from a file. Here my solution:

echo file('dayInt.txt')[1]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSang FroidView Question on Stackoverflow
Solution 1 - Phpuser557846View Answer on Stackoverflow
Solution 2 - PhpnimmneunView Answer on Stackoverflow
Solution 3 - PhpalexView Answer on Stackoverflow
Solution 4 - PhpPhilView Answer on Stackoverflow
Solution 5 - PhpbalanvView Answer on Stackoverflow
Solution 6 - PhpPhoenixView Answer on Stackoverflow
Solution 7 - PhpcantelopeView Answer on Stackoverflow
Solution 8 - PhpminerootView Answer on Stackoverflow
Solution 9 - PhpRikeshView Answer on Stackoverflow
Solution 10 - PhpSunitView Answer on Stackoverflow
Solution 11 - PhpDevin CamenaresView Answer on Stackoverflow
Solution 12 - PhpdruganView Answer on Stackoverflow
Solution 13 - PhpSamView Answer on Stackoverflow