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
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.

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.