I'm trying to create a variable with multiple lines but for some reason the <<<_END operator isn't working this is how the code looks:

<?php
$author = "Anon";
echo 
<<<_END
First Lines
Second Line.
Third Line.
- Written by $author.
_END;
?>

Why might it be?
I'm using php 5.2.14
on bitnami

not on my main computer but I will be using this pc for a good while so i need to fix that problem :p
Thanks!

Dani AI

Generated

The heredoc itself was fine in the examples posted by — the issue was how HTML displays the output, not PHP producing it. 's nl2br approach is a perfectly valid, simple fix when you want literal line breaks converted into HTML <br/> tags. Below are a few additional tips and alternatives that help avoid common heredoc pitfalls and give more control over how the text appears in a browser.

Heredoc notes and gotchas to watch for (PHP 5.2 era and later)

  • The closing identifier must start in column 1 with the semicolon immediately after it; no leading spaces or tabs are allowed in older PHP versions. An incorrectly indented closing marker causes a parse error.
  • Heredoc behaves like a double-quoted string, so variables are interpolated. If you need a literal block without interpolation, use nowdoc (available since PHP 5.3). See the PHP manual for details: Heredoc/Nowdoc reference.

Display options that preserve newlines without inserting raw <br/> tags

  • Wrap the output in a <pre> element (and use htmlspecialchars to avoid accidental HTML interpretation) to preserve the original whitespace and line breaks.
  • Use CSS white-space: pre-wrap; on a container to keep line breaks but still allow wrapping for long lines.
    Example approaches:
    echo '<pre>' . htmlspecialchars($str, ENT_QUOTES, 'UTF-8') . '</pre>';
    echo '<div style="white-space: pre-wrap;">' . htmlspecialchars($str, ENT_QUOTES, 'UTF-8') . '</div>';

Quick troubleshooting

Recommended Answers

All 8 Replies

any help :p

bump

What aspect of that is not working for you? That code works fine for me.

When I try it on the browsers all the text shows up in one line

Thats because newline characters are not the same as <br />. They are also not displayed on the output of the browser.

If you view the source of that output you will see that the text is actually on multiple lines.

thank you very much
seems I will have to keep using <br />

You have another option if you want to still use heredoc:

<?php
$author = "Anon";
echo 
$str = <<<_END
First Lines
Second Line.
Third Line.
- Written by $author.
_END;

echo nl2br($str);
?>

nl2br inserts <br /> tags before any new line characters in the string.

Thanks mate it worked perfectly!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.