Reading specific line of a file in PHP

I am working on reading a file in php.
I need to read specific lines of the file.

I used this code:

fseek($file_handle,$start);
while (!feof($file_handle)) 
{   
    ///Get and read the line of the file pointed at.
    $line = fgets($file_handle);
    $lineArray .= $line."LINE_SEPARATOR";

    processLine($lineArray, $linecount, $logger, $xmlReply);

    $counter++;
}
fclose($file_handle);

However I realized that the fseek() takes the number of bytes and not the line number.

Does PHP have other function that bases its pointer in line numbers?

Or do I have to read the file from the start every time, and have a
counter until my desired line number is read?

I’m looking for an efficient algorithm, stepping over 500-1000 Kb file to get to the desired line seems inefficient.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Use SplFileObject::seek

$file = new SplFileObject('yourfile.txt');
$file->seek(123); // seek to line 124 (0-based)

Solution 2

Does this work for you?

$file = "name-of-my-file.txt";
$lines = file( $file ); 
echo $lines[67]; // echos line 68 (lines numbers start at 0 (replace 68 with whatever))

You would obviously need to check the lines exists before printing though. Any good?

Solution 3

You could do like:

$lines = file($filename); //file in to an array
echo $lines[1];           //line 2

OR

$line = 0;
$fh = fopen($myFile, 'r');

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

Solution 4

You must read from the beginning. But if the file never/rarely changes, you could cache the line offsets somewhere else, perhaps in another file.

Solution 5

Try this,the simplest one

$buffer=explode("\n",file_get_contents("filename"));//Split data to array for each "\n"

Now the buffer is an array and each array index contain each lines;
To get the 5th line

echo $buffer[4];

Solution 6

You could use function file($filename) . This function reads data from the file into array.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply