Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Never ending while loop

Status
Not open for further replies.

dcomit

Technical User
Jun 20, 2001
115
GB
PHP Version 4.3.9 on linux

I’m not a php guru but I’ve modified a bit of php code to populate MySql tables from a pipe separated flat file. It works ok but won’t come out of a ‘while’ loop.

Code fragment below. dbwrite() is a function (not included here) which updates the database. The database gets updates ok but it doesn’t come out of the loop at eof. If I take out the dbwrite() function call and run the program it exits out of the loop ok.
Code:
#!/usr/local/bin/php -q
<?php
$file="/home/system/extract.txt";
if (file_exists($file)){
    $handle=fopen($file,"r");
} else die();
while (!feof($handle)) {
  $line=fgets($handle);
  $data=explode('|', $line);
  dbwrite($data);
}
fclose($handle);
?>
Any ideas welcome.

Thanks,
Dave
 
this can happen if the file isn't opening properly. but then i would be surprised that you are getting anything in your database.

could you try the following slight change to see whether it remedies the problem:
Code:
<?php
$file="/home/system/extract.txt";
if (file_exists($file)){
    $handle=fopen($file,"r")
      or die ("Can't open file");
    $fs = filesize($file);
} else die();
if ($fs > 0 ):
  while (!feof($handle)) {
  $line=fgets($handle);
  $data=explode('|', $line);
  dbwrite($data);
}
endif;
fclose($handle);
?>

you also might consider using file() instead of the fgets function. i have found it quicker:

Code:
<?php
$file="/home/system/extract.txt";
if ($lines = file($file)):
foreach ($lines as $line):
  $data=explode('|', $line);
  dbwrite($data);
endforeach;
else:
 echo "problem opening or reading file";
endif;
?>
 
I tried your first code example but it looped indefinitely. The second example worked fine and exited properly. However, the file I will be reading is large (in excess of 90 Mb.). I was led to believe that large files could cause problems when working with arrays.

Thanks,
Dave
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top