It works by opening the file without reading w3coded line specific anything, then moving the pointer instantly to a w3coded line specific random position, reading up to 4096 characters w3coded line specific from that point, then grabbing the first w3coded line specific complete line from that data.,He's exactly w3coded line specific right. For small files file($file); is perfectly w3coded line specific fine. For large files it's total overkill b/c w3coded line specific php arrays eat memory like crazy., w3coded line specific 4 w3coded line specific w3coded line specific By the way, feeding the entire file w3coded line specific into an array, such as with file() or w3coded line specific file_get_contents(), isn't recommended in w3coded line specific practice if you might be using any big files. w3coded line specific For small files it works great. w3coded line specific – Phoenix w3coded line specific Apr 25 '11 at 6:32 w3coded line specific w3coded line specific , w3coded line specific 18 w3coded line specific w3coded line specific Reading an entire file into w3coded line specific memory just to get the second line? I'd say that w3coded line specific is a recipe for disaster in some circumstances w3coded line specific (see Raptor's comment). w3coded line specific – Tomm w3coded line specific Jan 6 '15 at 8:04 w3coded line specific
$myFile = "4-24-11.txt";
$lines = file($myFile);//file in to an array
echo $lines[1]; //line 2
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
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++;
}
I would use the SplFileObject class...
$file = new SplFileObject("filename");
if (!$file->eof()) {
$file->seek($lineNumber);
$contents = $file->current(); // $contents would hold the data from line x
}
you can use the following to get all the lines in the file
$handle = @fopen('test.txt', "r");
if ($handle) {
while (!feof($handle)) {
$lines[] = fgets($handle, 4096);
}
fclose($handle);
}
print_r($lines);
Last Update : 2023-09-22 UTC 12:15:32 PM
Last Update : 2023-09-22 UTC 12:15:19 PM
Last Update : 2023-09-22 UTC 12:15:07 PM
Last Update : 2023-09-22 UTC 12:14:49 PM
Last Update : 2023-09-22 UTC 12:14:40 PM
Last Update : 2023-09-22 UTC 12:13:56 PM
Last Update : 2023-09-22 UTC 12:13:36 PM