unable to add line breaks. Why is it so?

时光总嘲笑我的痴心妄想 提交于 2019-12-24 16:22:41

问题


The following script prints the strings from the array named arr. After an echo from arr I try to insert a line break using \n but I don't see it. Why is that ?

<?php
$arr = array("ghazal","shayari","silence","hayaat");
echo $arr[0];
echo $arr[1];
foreach($arr as $var) {
  echo $var;
  echo "\n";
}

回答1:


HTML treats all whitespace characters, in any number, identically.

That is, the following will all render as a single space in the browser:

echo "\n";
echo "\t";
echo "         ";
echo "  \n\n\n  ";

In order to render an actual linkbreak in HTML, you need to insert a <br> element into your document.




回答2:


In HTML, the browser doesn't display \n linebreaks. If you view the source code, you will see them displayed. You can convert them to <br> using the nl2br PHP function, or by changing your script from this:

<?php
$arr = array("ghazal","shayari","silence","hayaat");
echo $arr[0];
echo $arr[1];
foreach($arr as $var) {
  echo $var;
  echo "\n";
}

to this:

<?php
$arr = array("ghazal","shayari","silence","hayaat");
echo $arr[0];
echo $arr[1];
foreach($arr as $var) {
  echo $var;
  echo "<br>";
}

And if this doesn't work for you, you could always use the pre HTML tag. The pre tag retains the \n linebreaks, and makes them visible.

If this helps, please mark this answer as correct by clicking the check next to this question.

Thanks. :)




回答3:


Presumably your PHP script is generating HTML that is viewed in a web browser. And, as we know, extraneous whitespace in HTML doesn't get rendered on screen.

Either generate plain text (header("Content-type: text/plain")) or output, instead of '\n', something that renders a line break in HTML (e.g. <br />).




回答4:


this should work

foreach($arr as $var) {
  echo $var;
  echo "<br />";
}

because in your HTML section <br /> work for linebreak, your \n also works when you see the source code of HTML from browser's side that time it shows you the linebreak




回答5:


Because line breaks are rendered in HTML with <br />. Do this instead.

foreach($arr as $var) {
    echo $var, '<br />';
}

An alternative would be to wrap the output in <pre></pre>, which evaluates whitespace and linebreaks like what you're doing currently.



来源:https://stackoverflow.com/questions/14392012/unable-to-add-line-breaks-why-is-it-so

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