Search code examples
phpwhitespace

PHP read white space in file


I have a file that looks like:

I       int result = 2 * n;
        result = result + 1;

II      int result = n + 1;
        result = result * 2;

III     int result = (n + 1) * 2;

I read and write the file with:

while(!feof($myfile)) {
    
    $line =  fgets($myfile) ;
    echo $line . "<br>";
}

the output I get is:

I int result = 2 * n;
result = result + 1;

II int result = n + 1;
result = result * 2;

III int result = (n + 1) * 2;

Is there a way to keep the extra spaces in the text to keep the spacing the same?


Solution

  • HTML does not preserve multiple spaces, so replace them with &nbsp;:

    while(!feof($myfile)) {
        
        $line =  fgets($myfile) ;
        echo str_replace(' ', '&nbsp;', $line) . "<br>";
    }