Reading a specific line of a file in PHP

I am working on reading a file in php. I need to read specific lines of a 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 it fseek()takes the number of bytes, not the line number.

Does PHP have another function that bases its pointer on line numbers?

Or do I need to read the file every time from the very beginning and have a counter until the number of the desired line is read?

I'm looking for an efficient algorithm, stepping over 500-1000 Kbytes of files to get the desired line seems inefficient.

+5
source share
6 answers

Use SplFileObject::seek

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

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

Obviously, you need to check if lines exist before printing. Any good?

+9
source

:

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

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

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

. / , - , , .

+1
source

Try it, simplest

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

Now the buffer is an array, and each array index contains each row; To get the 5th row

echo $buffer[4];
+1
source

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

0
source

All Articles