Have I misunderstood what heredoc should do?

[亡魂溺海] 提交于 2019-12-31 02:13:23

问题


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.


回答1:


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.




回答2:


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.




回答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.




回答4:


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.



来源:https://stackoverflow.com/questions/6058600/have-i-misunderstood-what-heredoc-should-do

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!