I'm trying to read a specific line from a text file using php. Here's the text file:
foo
foo2
How would I get the content of the second line using php? This returns the first line:
<?php
$myFile = "4-24-11.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
?>
..but I need the second.
Any help would be greatly appreciated
you can use the following to get all the lines in the file
and
$lines[1]
for your second lineThis question is quite old by now, but for anyone dealing with very large files, here is a solution that does not involve reading every preceding line. This was also the only solution that worked in my case for a file with ~160 million lines.
It works by opening the file without reading anything, then moving the pointer instantly to a random position, reading up to 4096 characters from that point, then grabbing the first complete line from that data.
You could try looping until the line you want, not the EOF, and resetting the variable to the line each time (not adding to it). In your case, the 2nd line is the EOF. (A for loop is probably more appropriate in my code below).
This way the entire file is not in the memory; the drawback is it takes time to go through the file up to the point you want.
If you use PHP on Linux, you may try the following to read text for example between 74th and 159th lines:
This solution is good if your file is large.
You have to loop the file till end of file.
If you wanted to do it that way...
Alternatively, open it with
file()
and subscript the line with[1]
.