Hi,
i'm writing this:
echo "foo";
echo "\n";
echo "bar";
and "bar" is not written in the line below.
What am i doing wrong?
Javi
Hi,
i'm writing this:
echo "foo";
echo "\n";
echo "bar";
and "bar" is not written in the line below.
What am i doing wrong?
Javi
PHP generates HTML. You may want:
echo "foo";
echo "<br />\n";
echo "bar";
Newlines in HTML are expressed through <br>
, not through \n
.
\n
creates a newline in the source code, and source code layout is unconnected to screen layout.
Assuming you're viewing the output in a web browser you have at least two options:
Surround your text block with <pre>
statements
Change your \n
to an HTML <br>
tag (<br/>
will also do)
If you want to write plain text, you must ensure the content type is set to Content-Type: text/plain
. Example:
header('Content-Type: text/plain');
If you are dealing with HTML, you have two options. One is to inset a new line using <br>
(Or <br />
for XHTML). The other is to put the plain text in a <pre>
element (In this case "pre" stands for preformatted).
It will be written on a new line if you examine the source code of the page. If you want it to appear on a new line when it is rendered in the browser, you'll have use a <br />
tag instead.
if your text has newlines, use nl2br php function:
<?php
$string = "foo"."\n"."bar";
echo nl2br($string);
?>
This should look good in browser
If you want a new line character to be inserted into a plain text stream then you could use the OS independent global PHP_EOL
echo "foo";
echo PHP_EOL ;
echo "bar";
In HTML terms you would see a newline between foo and bar if you looked at the source code of the page.
ergo, it is useful if you are outputting say, a loop of values for a select box and you value having html source code which is "prettier" or easier to read for yourself later. e.g.
foreach( $dogs as $dog )
echo "<option>$dog</option>" . PHP_EOL ;