Search code examples
phphtmlfgets

The result of "echo fgets()" in a txt file is not the same


I am trying to include in my website a txt file with php using the following code

    <?php 
      $myFile = '[http://users.otenet.gr/~vag1976/optonio/NOAAMO.TXT]';
      $fp = fopen("$myFile", "r");
      while(!feof($fp)) { 
        echo fgets($fp) . "<br />";
      }
      fclose($fp);
    ?>

The problem is that using this php code the result is not exactly the same as the original. The gaps (spaces) between the words are lost and are replaced by only one space. The viewing result is terrible. Any ideas?


Solution

  • That's not a PHP problem, it's just the browser which does not render multiple 'normal' spaces (if you don't use non-breaking-spaces &nbsp; or the special <pre> tag).

    You should also use a real line feed instead of <br /> tags:

    <?php 
      $myFile = '[http://users.otenet.gr/~vag1976/optonio/NOAAMO.TXT]';
      // You don't need to use "$myFile" here, just use the variable without quotes
      $fp = fopen($myFile, "r");
      echo "<pre>";
      while(!feof($fp)) { 
        echo fgets($fp) . "\n";
      }
      echo "</pre>";
      fclose($fp);
    ?>
    

    If your file is not too large, you can also use file_get_contents():

    <?php
      $myFile = '[http://users.otenet.gr/~vag1976/optonio/NOAAMO.TXT]';
      echo '<pre>' . file_get_contents($myFile) . '</pre>';
    ?>