ToddAtWSU Posted August 22, 2007 Share Posted August 22, 2007 I am using PHP to read a file and I was just using fgets to get my line and using a for-loop until the line was EOF, then I would break out of my loop. I noticed this has a problem when the file I read from has blank lines at the end. I have tried to ignore these blank lines at the end of the file but I cannot get them to be ignored. My code looks like: <?php $team; $totalGames; function getTeams( ) { global $team; $fp = fopen( 'teams.txt', 'r' ); if( $fp ) { for( $i = 0 ; !feof( $fp ) ; $i++ ) { $temp = fgets( $fp, 128 ); if( strcmp( $temp, "\n" ) != 0 ) { $team[$i] = $temp; } } } fclose( $fp ); } ?> But for some reason I am always entering the if-statement. What should I be checking for in my if-statement. The person providing the file may not always remove the blank lines at the end so I want to ignore them and not rely on a smart end-user. I have tried checking for "\n", "\r", "\r\n", "\n\r", " ", and "". The file is modified in Windows. Thanks for your help. Quote Link to comment Share on other sites More sharing options...
Fadion Posted August 22, 2007 Share Posted August 22, 2007 For the file() function in the php manual, there is: FILE_SKIP_EMPTY_LINES Skip empty lines So u can use a similiar code: $text = file('teams.txt', FILE_SKIP_EMPTY_LINES); foreach($text as $lines){ echo $lines; } If it doesnt work try conditioning with strlen() > 0 or probably some regex. Quote Link to comment Share on other sites More sharing options...
ToddAtWSU Posted August 22, 2007 Author Share Posted August 22, 2007 I am used to the more C-oriented functions like fopen( ) and fclose( ) that I did not know about the file( ) function. It appeared it would work but unfortunately, it did not store the data in my global array. So I tried the strlen( ) idea like you mentioned instead of strcmp( ) and that worked like a charm! Thanks for your help! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.