3

I'm very new to PHP so I know I am missing something obvious here - I thought the heredoc function is supposed to retain formatting, line breaks, etc. But whenever I test it, while it parses, there is no formatting. I've tried lots of different scripts including copy-and-pasts from sources such as PHP.net and W3schools - so I know there is nothing wrong with the scripts. Can't google up an answer to this one - probably because it's too obvious?? (BTW, testing with MAMP). Thanks.

Lex
  • 31
  • 2

4 Answers4

4

HEREDOC is not a function, it is a method for specifying string delimiters that allows you to forgo escaping quotes within the heredoc (I like it because good text editors will syntax highlight their contents based on the heredoc name).

HEREDOCs do preserve all whitespace, newlines, etc. I think you are probably looking at the results in a browser. Browsers generally trim all whitespace, newlines, spaces, and tabs included, down to a single space. Try looking at it on the command line, a text email, or a text file.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • Thanks Tandu! I am indeed viewing in browsers. Sorry if this question is, again, too obvious... will it be treated differently by browsers once uploaded to my server as opposed to MAMP? I guess I am looking for the best way to move between HTML and PHP. – Lex May 19 '11 at 12:37
  • PHP should treat the html exactly the same, but you can't guarantee how a browser is going to treat your HTML. Just test in all major browsers and find the best compromise (for plain text you're usually okay). – Explosion Pills May 19 '11 at 12:41
3

It will produce a string identical to the one you set.

However, browsers render multiple whitespace condensed to one space character. This is by design.

To preserve your spaces, you can use the pre element (assuming default browser stylesheet) or white-space: pre CSS property.

<div style="white-space: pre">
<?php echo <<<A
some text
    preserved
        just
    how
 you want it.
A; ?>
</div>

jsFiddle.

alex
  • 479,566
  • 201
  • 878
  • 984
3

Because you said "testing with MAMP" I assume, that you use your webbrowser to display the content. Thats a slightly wrong approach, because the webbrowser itself strips down any unnecessary whitespaces. Look at the source of the page you display in your browser and you will see the "real" content.

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
0

It does, but only for what it outputs.

If it outputs HTML, then that HTML is going to be interpreted by a browser using the normal rules for handling whitespace.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335