J0n 3laze posted on 2009-02-19 15:16:25 #
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
The most popular forum posts:
Comments / discussions
Olaf posted on 2009-02-19 15:31:13 #
don't know why people do that this way :)
try
$data = file('test.txt');
foreach ($data as $val) {
//do stuff with $val here
}
J0n 3laze posted on 2009-02-19 20:12:27 #
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.
Olaf posted on 2009-02-19 20:16:23 #
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.
J0n 3laze posted on 2009-02-19 23:20:22 #
thank you that worked perfectly.