Can a for loop be done with feop()?
| SitePoint Sponsor |

Can a for loop be done with feop()?



Not a for loop, but
PHP Code:$fh = fopen('myFile.txt','r');
$fileContent = '';
while (!feof($fh)) {
$fileContent .= fread($fh,1024);
}
fclose($fh);

Maybe there is a better way for me to do this. What I am trying to do is the following:
1) Read a file using fopen
2) I need to be able to skip the first 2 lines and the last 2 lines
My current method is the same as you have posted above but I am not able to skip the first 2 lines and the last 2. Is there any way I can achieve this with the method that you posted?
EDIT: I am staying away from count(file("text.txt")) because the files I am dealing with have about 900,000 lines.





Sounds silly but could you not explode the text into an array of lines, remove the 4 lines and then implode it (if required)?
edit: With the loop, you'll need to count the lines, thus you'd always have to use count(file("text.txt")) to find out how many lines there are so you know when to remove the last two. Shifting and popping the first and last two lines would seem the only easy way to do it.



fread() doesn't actually read a line at a time anyway, but fgets can read a line at a time. Slightly quirky, but you can easily discard the first two lines:
Then read the next two lines into an array:PHP Code:$fh = fopen('myFile.txt','r');
$discard = fgets($fh);
$discard = fgets($fh);
Then loop till feof(), actually reading the next line, but processing the first in the array before unshifting it when you've finished with it.PHP Code:$fileArray[] = fgets($fh);
$fileArray[] = fgets($fh);
PHP Code:while (!feof($fh)) {
$fileArray[] = fgets($fh);
processLine(array_shift($fileArray));
}
Bookmarks