tags:

views:

211

answers:

8

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

+2  A: 

PHP generates HTML. You may want:

echo "foo";
echo "<br />\n";
echo "bar";
Daniel A. White
there is no need for the \n there
Hendrik
PHP does not *generate* HTML.
Felix Kling
Looks like @Hendrik you have never had to debug *generated* HTML source code
Col. Shrapnel
@Felix care to share your brilliant knowledge of proper terminology?
Col. Shrapnel
@Col. Shrapnel: Sure. PHP just outputs text (characters), nothing more nothing less. It depends what you do with the output. E.g. the OPs code would create the desired result when run from the commandline. Saying that *PHP generates HTML* is just wrong.
Felix Kling
+4  A: 

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.

Tomalak
+2  A: 

Assuming you're viewing the output in a web browser you have at least two options:

  1. Surround your text block with <pre> statements

  2. Change your \n to an HTML <br> tag (<br/> will also do)

Mark E
+9  A: 

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).

Yacoby
Please explain the downvote? It would be good to know what was wrong with my answer so that I can correct it.
Yacoby
+1  A: 

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.

Matt
A: 
echo "foo<br />bar";
McNabbToSkins
A: 

if your text has newlines, use nl2br php function:

<?php
$string = "foo"."\n"."bar";
echo nl2br($string);
?>

This should look good in browser

Andrei Railean
A: 

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 ;
Cups
I'd say `echo "<option>$dog</option>\n";` is way readable than yours
Col. Shrapnel
But it wouldn't be OS independent so would be less portable, and I was claiming that the generated HTML source code would be more readable - but actually I find lines containing PHP_EOL easier to scan because I can tell where its headed.
Cups