string - Heredoc is not working. (PHP)
I tried to run this code to print the output in multiple lines, but it is not working as expected.
<?php
$author = "Bill Gates";
$text = <<<_END
Success is a lousy teacher.
It seduces smart people into thinking they can't lose.
-$author
_END;
echo $text;
?>
The indentation is perfectly fine but still the output is in one line.
Here's the output
I thought there is an error in my code so I copied the below code from the official PHP website
<?php
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
/* More complex example, with variables. */
class foo
{
var $foo;
var $bar;
function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'MyName';
echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>
Even this code gives output in one line. Output 2
So, why does it happen like that? What is the error? Thanks in advance!
Answer
Solution:
Your browser is handling the output and displaying it. The reason is that there is no HTML formatting telling it to "line break", split it up into multiple lines. To cause the
\n
to line break in a browser you have to use the<br>
tag.You can use the function
nl2br()
as follows:Now there are line breaks.
With your code at the top all you have to do is
echo nl2br($text);
and you will get the line breaks, multiple lines.Answer
Solution:
Heredoc syntax has nothing to do with telling a browser which character to use as a newline character to generate multi-line output.
Web browsers use
<br>
, and not'\n'
which this string has, to display a new lineWhat you are expecting can be done with sending a
<pre>
tag to browser before any output.There is no HTML linebreak in this code, regardless of how the string was created. If you want the output to be shown preformatted just send a
<pre>
tag before the output and then we don't need those HTML line breaks.Will generate same output as
Or just send some
<br>
s. And as the other answer suggests, you can convert those newline chars to<br>
using that function