Reputation: 11
So I am getting the contents out of a text file using a while loop and an array and then echoing it out. It works except for one problem which is the last line:
First name: john Last name: paul Age: 44
First name: sam Last name: smith Age: 22
First name: jim Last name: bob Age: 33
First name: Last name: Age:
My question is why does it loop again if it is at the end of the file and how do I get rid of the last line?
<?php
$fileread = fopen("textfile.txt", "r");
while (!feof($fileread)){
$list = fgets($fileread);
$arrayinfo = explode(",", $list);
echo "<b>First name: </b> " . $arrayinfo[0] . " " . "<b>Last name: </b>" . $arrayinfo[1]. " " . "<b>Age: </b>" . $arrayinfo[2] . "<br>";
}
fclose($fileread);
?>
Upvotes: 1
Views: 119
Reputation: 2057
I'm not sure why it reads the loop runs again after the last line. My guess is below. Someone who knows more is welcome to correct me.
I suspect that the EOF is a character at the end of the file. The last fgets reads the line up to a "\n" or "\r" character which comes just before the EOF character. Therefore the !feof($fileread)
test is still TRUE resulting in one final read where $list is likely empty.
I'm not sure what you can do about it except run a test on each line like the following:
if (empty($list)) { break; }
which would come just before $arrayInfo = explode...
.
Edit: If you have a comma at the end of the file (on it's own line) then the empty check will return false and you will still print an empty line. So if:
if (empty($list)) { break; }
doesn't work then try
if (strlen($list) < 2) { break; }
This will work as long as there any spaces or such that go along with a comma at the end of the line. Past that you could test the result of explode gave you 2 usable fields liek this:
if (empty($arrayInfo[0]) || empty($arrayInfo[1])) { break; }
These problems frequently revolve around stray chars in the file so make sure the file is clean to test your logic. Then if the input files aren't all clean build filters to deal with the unclean real data.
Upvotes: 0
Reputation: 23011
It sounds like there's a new line at the end of the file. You can check to make sure that $arrayinfo is not empty before you echo:
if(!empty($arrayinfo))
echo "<b>First name: </b> " . $arrayinfo[0] . " " . "<b>Last name: </b>" . $arrayinfo[1]. " " . "<b>Age: </b>" . $arrayinfo[2] . "<br>";
Upvotes: 2