Question

I've just started the O'Reilly book on PHP, MySQL and JavaScript and I've just got to the stage where I learn about heredocs. It says in the book they preserve text literally, however mine doesn't at all. I've even copied the code exactly as it is in the book and it's still not behaving and I'm told it should.

I want my code to preserve the linebreaks within the heredoc but it just doesn't want to, the only way I can get it to do so is to use the "< br />" tag.

Here is my code:

<?php
$author = "Bobby McBobson";

$text = <<<_END
This is a Headline.

This is the first line.
This is the second line.
- Written by $author.
_END

echo $text;
?>

No matter what variation of the code I use it always comes out like so:

This is a Headline. This is the first line. This is the second. -Written by Bobby McBobson

Whereas I'd like it to come out as:

This is a Headline.

This is the first line.
<br/>This is the second.
<br/>-Written by Bobby McBobson

Even on here I've had to use the < br /> tag (broken up for obvious reasons), so I'm thinking there's something fundamental I'm missing?

Was it helpful?

Solution

The line breaks are preserved but, when written as HTML, those line breaks lose their meaning; to add formatting in HTML you should use nl2br():

echo nl2br($text);

You could also wrap them inside <pre> or some other tag that has the white-space: pre; style.

OTHER TIPS

<?php
$author = "Bobby McBobson";

$text = <<<_END
This is a Headline.<br /><br />

This is the first line.<br />
This is the second line.<br />
- Written by $author.<br />
_END;

echo $text;
?>

works fine for me, don't forget the semicolon after END to close the variable $text definition. You really need the <br /> tags if you want a new line otherwise it will just interpret as text. EDIT: Actually the code without HTML stays formatted when I try it on http://sandbox.onlinephpfunctions.com/ but loses its formatting on http://writecodeonline.com/php/

Not sure why?

This is quoted from the book. It's a page or so further on.

Laying out text over multiple lines is usually just a convenience to make your PHP code easier to read, because once it is displayed in a web page, HTML formatting rules take over and whitespace is suppressed (but $author is still replaced with the variable’s value). So, for example, if you load these multiline output examples into a browser they will not display over several lines, because all browsers treat newlines just like spaces. However, if you use the browser’s view source feature, you will find that the newlines are correctly placed, and the output does appear over several lines.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top