Link to home
Start Free TrialLog in
Avatar of IT79637
IT79637Flag for United States of America

asked on

How to correctly terminate a text file line so read into PHP?

Hi,

I'm attempting to read a text file using a PHP script and write the data to a MySQL DB.  I'm using PHP version 5.1.4.

I can't get past reading the file.  The code and error messages are shown below.  The image is the text file converted to Hexadecimal.

Note, the end of line characters in hex are: 0D 0A.  Is this correct?  I'm using Ultra Edit to create the test file.  Could my editor be the problem?

How do I fix this?

Thanks!

 


<?php
  $myfile = "C:\\tmp\\text.txt";
  $fh = fopen($myfile, 'r') or die("Can't open file");
  while (!feof($myfile)) {
    $line = fgets($file);
    echo ($line)."<br>";
  }
  fclose($file);
 ?>
  
?>

Warning: feof(): supplied argument is not a valid stream resource in E:\Program Files\nusphere\phped\Projects\ParsMetData&InsertIntoDB.php on line 5

Warning: fgets(): supplied argument is not a valid stream resource in E:\Program Files\nusphere\phped\Projects\ParsMetData&InsertIntoDB.php on line 6

Open in new window

php1.jpg
ASKER CERTIFIED SOLUTION
Avatar of neorush
neorush

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
See http://php.net/manual/en/function.file.php

If you try file() and find blank lines between every valuable line of data, you might want to trim() each line as you read it, then add back the PHP end-of-line character which is always found in the constant PHP_EOL.  It is context-aware.

In case you are reading information from a comma-separated type of file, you might find this function useful.
http://us.php.net/manual/en/function.fgetcsv.php

Best regards, ~Ray
Avatar of IT79637

ASKER

Thanks!