Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic space after fgets' result?

Tags:

php

fgets

space

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 :-)!

like image 750
Chris Avatar asked Aug 18 '10 14:08

Chris


2 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
like image 99
Frxstrem Avatar answered Oct 19 '22 00:10

Frxstrem


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

like image 40
Brandon Horsley Avatar answered Oct 18 '22 23:10

Brandon Horsley