PHP: Read Specific Line From File

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


$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


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.

Tags:

Php

File

Line