开发者

Newlines not working in PHP?

This is my complete web page, with php code taken direct开发者_JAVA技巧ly from here. Yet all the text on the page renders on a single line?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>

<?php

echo "This spans
multiple lines. The newlines will be
output as well";

echo "This spans\nmultiple lines. The newlines will be\noutput as well.";

?>

</body>
</html>


The newlines are there in your source code. Browsers, however, won't render newlines as line breaks on your page, so you need to use line break tags (<br />) instead.


HTML does not support newlines, therefore you must use <br>.

You could use nl2br which will convert all your \n in your string, to <br> which will generate your desired output.


HTML will coalesce consecutive whitespace (in most contexts) to a single space character. You'll either need to output paragraphs (<p>...</p>) or other tags with border or padding, or output explicit line-breaks (<br>).


The newlines do indeed get printed, but HTML does not care about whitespace (unless you explicitly tell it to, look at pre element and white-space: pre).

Browsers will essentially turn all \s into one space when viewing HTML.


Oh, the new lines are there and they are working. Take a gander at the HTML source (i.e when you right-click on the browser and select View Page Source) and not the results being displayed in the browser. You'll see the new lines there.

The problem is that HTML itself does not care about how you format your white space. To HTML all white space, whether a tab, a new line, or a whole mess of spaces is translated as a single space.

To get HTML to display line breaks, you'll have to use HTML tags such as <pre>, <p>, or <br/>.

I find it easier in PHP programs to create my own echoLine function that adds in both the \n and a <br/>. That way, I see it in both the webpage source and the HTML display.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜