Have I misunderstood what heredoc should do?

后端 未结 4 1008
小鲜肉
小鲜肉 2021-01-20 13:03

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

相关标签:
4条回答
  • 2021-01-20 13:23

    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.

    0 讨论(0)
  • 2021-01-20 13:37

    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.

    0 讨论(0)
  • 2021-01-20 13:40

    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.

    0 讨论(0)
  • 2021-01-20 13:46

    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.

    0 讨论(0)
提交回复
热议问题