Jump to content

[SOLVED] Blank lines in files


ToddAtWSU

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/66076-solved-blank-lines-in-files/
Share on other sites

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.

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! ;D

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.