tinks
tinks

Reputation: 323

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.

Upvotes: 8

Views: 16538

Answers (6)

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205

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++;
}

Upvotes: 5

JRL
JRL

Reputation: 78033

Use SplFileObject::seek

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

Upvotes: 15

Victor Kuznetsov
Victor Kuznetsov

Reputation: 284

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

Upvotes: 0

ale
ale

Reputation: 11830

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?

Upvotes: 11

Akhil Thayyil
Akhil Thayyil

Reputation: 9413

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

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799490

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.

Upvotes: 1

Related Questions