• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 426
  • Last Modified:

feof doesn't work on remote fgets call

The following code snippet works great, with one slight problem....

if(!($File=@fopen($url,"r")))  // $url = http://www.somedomain.com/somepage.htm?var1=var
{ echo "couldn't read $url "; exit; }

while (!feof($File)) {
 $Line.=fgets($File,255);
}
fclose($File);

The page I'm retrieving is just a plain html table with roughly 20 rows, but the last few characters are always missing. I've tried various line sizes, but still get the same results.  According to a note in the PHP manual, you can't look for feof on a remote file, which seems to be the cause of the missing characters.  

How could the above snippet be re-written to not use feof, and hopefully, not drop the last few characters?
0
dewed
Asked:
dewed
1 Solution
 
lozlozCommented:
hi,

why not swap

while (!feof($File)) {
 $Line.=fgets($File,255);
}

with:

$contents = "";
do {
    $data = fread($File, 8192);
    if (strlen($data) == 0) {
        break;
    }
    $contents .= $data;
} while(true);

loz
0
 
dewedAuthor Commented:
Im a bit embarresed here. I tried lozloz solution and was amazed that it didn't give me different results...
Turns out the whole problem was just below the code posted above...

$start_position=strpos($Line, $start);
$end_position=strpos($Line, $end)+strlen($end);
$length=$end_position-$start_position;
$Line=substr($Line, $start_position, $length);

because $end did not equal any part $Line , the last line was dropped. I surrounded that block with an if, so if $url had a particular substring, the start/end block above wasn't executed.. it now works perfectly with either my or lozoz's code.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now