fgets() failure on blank lines EOF

Posted by J0n 3laze #

I am reading a text file line by line until end of file using the feof and fgets() functions.

while(!feof($fstrm))
{
$myData = fgets($fstrm) or die('unable to read line');
//do stuff with it here
}

This code executes perfectly...unless there is a blank line at the end of my file.
What would be the best way of either ignoring blank lines or removing them before the function chokes?
I am fairly new using PHP and have mostly used c# and vb. I did notice there is a trim() function for PHP as well, however I don't want to remove carriage returns or line feeds. I only want to remove the last line of the file if it is blank.
Thank you

Comments / discussions

Posted by Olaf #

don't know why people do that this way :)

try

$data = file('test.txt');
foreach ($data as $val) {
    //do stuff with $val here
}

Posted by J0n 3laze #

hmm...
The file() function reads the entire file into an array.
So essentially this would be looping through each array value, allowing me to manipulate the data and continue until the end of the array. Does this automatically flush out null values in the array or would I need to use the trim() function on each $val?

Thank you for your prompt response.

Posted by Olaf #

the file function is great for smal to medium data files, if you need to test empty rows just do it this way:

if (trim($val) != '') echo 'this is a row';

I used the file function to import thousands of database records from a standard text file.

Posted by J0n 3laze #

thank you that worked perfectly.