Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading specific line of a file in PHP

Tags:

file

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.

like image 817
tinks Avatar asked Feb 21 '12 08:02

tinks


People also ask

How to read specific line from file in php?

PHP Read Single Line - fgets() The fgets() function is used to read a single line from a file.

Which of the following is the correct way to open read text file in PHP?

Answer: (a) fopen("sample. txt", "r"); Description: The fopen() function accepts two arguments: $filename and $mode.


2 Answers

Use SplFileObject::seek

$file = new SplFileObject('yourfile.txt');
$file->seek(123); // seek to line 124 (0-based)
like image 63
JRL Avatar answered Oct 24 '22 16:10

JRL


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?

like image 42
ale Avatar answered Oct 24 '22 15:10

ale