Black
Black

Reputation: 20402

Why does fgets adds a space at the end of string?

I have a file which contains a single string. I open the file and read the value, with fopen and fgets, i noticed that a space is added at the end of the string.

$file = fopen("myfile", "r") or exit("<br><p>Unable to open file</p><br>");
$mystring= fgets($file);
fclose($file);

Content of myfile:

Hello

Test

echo "<p>'".$mystring."'</p>";    //Output:   'Hello '

As you can see there is now a space at the end of the string, even though there is no space in the file.

I tried the same with the linux command "cat":

$mystring = shell_exec("cat myfile");
echo "<p>'".$mystring."'</p>";    //Output:   'Hello '

Still a space at the end of the string.

My goal is to compare the string in the file, with a value in my code.

if ($mystring === "Hello")
{
    echo "Equal";
}
else
{
    echo "not equal";
}

I always get "not equal". How can i read and store the actual file content into my variable?

Upvotes: 1

Views: 1670

Answers (3)

Rahul Kate
Rahul Kate

Reputation: 700

This could be the case of differences in line endings like MsDos, Unix or Mac. You can use the function auto_detect_line_endings. (More info here).

Or you can simply trim the text from the output file before comparison as given below.

$file = fopen("myfile", "r") or exit("<br><p>Unable to open file</p><br>");
$mystring= fgets($file);
$mystring= trim($mystring);
fclose($file);

Upvotes: 1

Salic
Salic

Reputation: 49

) There's quite a number of things that could be wrong. I would start with inspecting the variable contents - Debugging if you can, or use a var_dump.

A nice way to get around the problem would be to use file_get_contents() instead (http://php.net/manual/de/function.file-get-contents.php). I think that is exactly made for this kind of problems ;)

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324840

To debug a string, try this:

foreach(str_split($mystring) as $chr) {
    printf("[%02x] %s <br />",ord($chr),$chr);
}

This should, in your case, yield something like...

[48] H
[65] e
[6c] l
[6c] l
[6f] o
[0a]

Take note of that last one. 0x0a is a newline character, which is what all lines of text obtained through fgets and shell_exec end with, since that's what marks the end of the line (both functions return a "line" of output from their respective activity).

(Note: You may get [0c] [0a], or a CRLF, depending on your system.)

To fix, just use rtrim() on the string before handling it.

EDIT: Since you added in a comment that the case of 'hello ' should be allowed, then you can use something more explicit, like rtrim($mystring, "\r\n");

Upvotes: 3

Related Questions