Reputation: 65
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!
Upvotes: 1
Views: 1783
Reputation: 46900
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 line
What you are expecting can be done with sending a <pre>
tag to browser before any output.
The indentation is perfectly fine but still the output is in one line.
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.
<pre>
<?php
echo "La la la
la la la la
la la la la";
?>
Will generate same output as
<pre>
<?php
echo <<<TEXT
La la la
la la la la
la la la la
TEXT;
?>
Or just send some <br>
s. And as the other answer suggests, you can convert those newline chars to <br>
using that function
Upvotes: 3
Reputation: 10400
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:
$myString = <<<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;
echo nl2br($myString);
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.
Upvotes: 3