Home » Php » php – Automatic space after fgets' result?

php – Automatic space after fgets' result?

Posted by: admin July 12, 2020 Leave a comment

Questions:

it seems as if fgets puts a space after everything it returns.
Here’s some example code:

<?php
Echo "Opening " . $_SERVER{'DOCUMENT_ROOT'} . "/file.txt" . "...<br>";
$FileHandle = @Fopen($_SERVER{'DOCUMENT_ROOT'} . "/file.txt", "r");
If ($FileHandle){
    Echo "File opened:<br><br>";
    While (!Feof($FileHandle)){
        $Line = Fgets($FileHandle);
        Echo $Line . "word<br>"; //Should be LINECONTENTSword, no space.
    }
    Fclose($FileHandle);
}
?>

which returns

Opening /var/www/vhosts/cqe.me/httpdocs/file.txt...
File opened:

First line word
Second line word
3rd line word
Another line of text word
Blablablaword

Why is there a space between the line’s content and “word”?
And why is this space not there at the end of the file (Blablablaword)?

Could you please tell me how to get rid of this space?
Thanks a lot :-)!

How to&Answers:

fgets() returns a line and the newline character (\n). This would then, as all other whitespaces, be rendered as a space in HTML.

To remove the trailing newline, use

$line = rtrim($line, "\r\n");
// Trims \r, \n and \r\n, which are all considered
// newlines on different platforms

Answer:

I believe fgets returns the end of line character (\n) also, and this is rendered as a space in html.

If you want to remove all trailing space from the line, you could use rtrim