Solved

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

Posted on 2011-09-28
319 Views
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

php1.jpg
0
Question by:IT79637

LVL 6

Accepted Solution

neorush earned 300 total points
ID: 36719408
Actually your file is fine, the code is incorrect.  You need to use the file handler resource $fh with the file handler functions (feof, fgets, fclose) <?php$myfile = "C:\\tmp\\text.txt";
$fh = fopen($myfile, 'r') or die("Can't open file");
while (!feof($fh)) {$line = fgets($fh); echo ($line)."<br>";
}
fclose(\$fh);
?>

0

LVL 109

Expert Comment

ID: 36719850
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
0

LVL 1

Author Closing Comment

ID: 36720113
Thanks!
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
The viewer will learn how to dynamically set the form action using jQuery.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.