php newline not working - php

For some reason i cant get the carriage return to appear on the web page. When i view source code it is fine.
I have tried various iterations of \n but it is kicking my butt.
<?php
/* Define string */
$greeting = "Greeting Professor Falken.";
$question1 = "Would you like to play a Game?";
print "$greeting \n ";
print "$question1";
?>

header('Content-type: text/plain');

Use <br /> instead. HTML renderers strips all white space which includes /n. If you want the newlines to be displayed (for example in text blocks), surround them with <pre></pre>

Wrap your code in <pre> tags or use <br /> instead.

Try:
header('Content-type:text/plain');
and if for windows \r\n

There's also the method for the lazy:
ob_start("nl2br"); // at the begin of a script

Related

PHP: Character escaping not working with double quotes unless there is a <pre> tag?

Please can someone tell me where I'm going wrong?
//outputs : Hi, my name is Jackal I like PHP
<?php
echo "Hi, my name is Jackal \nI like PHP";
?>
Whereas if I use pre tag
//outputs: Hi, my name is Jackal
// I like PHP
<pre>
<?php
echo "Hi, my name is Jackal \nI like PHP";
?>
Can someone please explain why character escaping isn't working?
thanks
PHP is interpreting that line break. Look in the source code of the webpage. You'll see that you have 2 lines in the source.
However, HTML handles line breaks differently. To perform a line break in HTML, use the <br> tag. This will make the HTML output over 2 lines on the webpage itself. However, in the source code, it will still appear as a single line (unless you add that line break).
What <pre> is doing is telling the HTML engine to output the exact string as-is since the text is preformatted, including interpreting that line break. Also note, you should add a closing </pre> tag at the end of the block that is preformatted.
If you have this in your HTML:
<p>Hello,
World!</p>
Does it appear on one line, or two?
Usually, the answer is one: whitespace is condensed into a single space.
<pre>, however, has the default CSS of white-space:pre, which does NOT condense whitespace.
You should echo "<br />", or apply white-space:pre (or, even better, white-space:pre-wrap) to the container element.
Because in your browser \n shows just a whitespace and does not appear as line break unless you use pre-formatted HTML tag <pre>.
e.g. following will display with a line break in browser:
echo "Hi, my name is Jackal <br />I like PHP";
or this one also:
echo "<pre>Hi, my name is Jackal \nI like PHP</pre>";
As you can make out that <pre> tag is for displaying pre-formatted text hence \n does show as line break.
Character escaping is working. Look at the source code, there you'll find the new line. In order to make it visible in a browser you need an html tag (<br />) or the wrapping <pre>
<br>
is HTML.
<br />
is XHTML (recommended).
\n
is a newline in the code (works while writing to file, but doesn't output to the screen).
alternately you can use nl2br as below
echo nl2br("Hi, my name is Jackal \nI like PHP");
The newline character in php actually echos a new line itself.
However, the output of php's echo statement is still the source code of the web browser. Hence, the browser condenses all the extra line breaks and spaces. For example:
<p>Hello
there</p>
outputs
Hello there
despite the white space. To get around this issue, use the <br>/<br/> tag to tell the browser to make a newline, instead of tell php to make a newline.

PHP heredoc not retaining format

Using the following code I expect to see 5 separate lines displayed. Instead it wraps everything together on one line... no tabs, no leading spaces, no blank line. Not what I was expecting.
After viewing other code, the programmer inserted a series of 's which I tried (using instead) and got some of the results I was looking for. Am I expecting too much? I never could get leading spaces and tabs to work. Could this be a setup problem?
<?php
$author = "Alfred E Newman";
$out = <<<_END
This is a Headline
This is the first line.
This is the second.
- Written by $author.
_END;
print $out;
// echo $out; // ... didn't format as expected either
?>
Result: This is a Headline This is the first line. This is the second. - Written by Alfred E Newman.
If you're outputting to HTML, try wrapping the print call in <pre> tags. A browser doesn't pay attention to OS newline characters when displaying HTML. BUT, if you view the page's source code you'll see the output formatted as expected there.
If you want new lines displayed in your HTML, you'll have to use <br/> or <p> or an appropriate CSS styling mechanism.
UPDATE
Oh and I forgot! As mentioned by the ever-vigilant #MarkBaker (thanks), PHP's nl2brdocs function will handle such an operation for you by replacing newline characters with <br/> tags:
$output = nl2br($output);
print $output;
Just add a header('Content-Type: text/plain;'); on top of your script:
<?php
header('Content-Type: text/plain;');
$author = "Alfred E Newman";
...
This tells your browser that it should display the output as plain text (not as HTML).

Print text including line returns in PHP

I am pulling text from a database and I want to print out the text and include the line returns so the text is readable and not all compressed into one paragraph.
Is this possible and if so what is the PHP function.
Thank you in advance.
The problem you have is that you get \n out of the database. Because HTML ignores whitespace, then those \n will be ignored by your browser.
You can use the nl2br function to convert all \n to <br /> tags.
you can use the HTML < pre > tag or nl2br($string)
You could either change the header to text/plain:
header("Content-type: text/plain");
echo $db_text;
Or you could replace new lines with breaks:
echo nl2br($db_text);

PHP: trying to create a new line with "\n"

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
Newlines in HTML are expressed through <br>, not through \n.
Using \n in PHP creates a newline in the source code, and HTML source code layout is unconnected to HTML screen layout.
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 ;
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).
PHP generates HTML. You may want:
echo "foo";
echo "<br />\n";
echo "bar";
if your text has newlines, use nl2br php function:
<?php
$string = "foo"."\n"."bar";
echo nl2br($string);
?>
This should look good in browser
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)
Since it wasn't mentioned, you can also use the CSS white-space property
body{
white-space:pre-wrap;
}
Which tells the browser to preserve whitespace so that
<body>
<?php
echo "hello\nthere";
?>
</body>
Would display
hello
there
We can use \n as a new line in php.
Code Snippet :
<?php
echo"Fo\n";
echo"Pro";
?>
Output:
Fo
Pro
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.
This works perfectly for me...
echo nl2br("\n");
Reference: http://www.w3schools.com/php/func_string_nl2br.asp
Hope it helps :)
This answer was so obvious and it took me forever to figure out:
echo "foo
bar";
I know that looks like it's wrapping. It's not. What I did is I literally hit return halfway through the string, between foo and bar. It creates a new line in the HTML source and makes your PHP look horrible. This was in Linux/Apache.
echo "foo<br />bar";
We can apply \n in php by using two type
Using CSS
body {
white-space: pre-wrap;
}
Which tells the browser to preserve whitespace so that
<body>
<?php
echo "Fo\n Pro";
?>
</body>
Result:
Fo
Pro
Using nl2br
nl2br: Inserts HTML line breaks before all newlines in a string
<?php
echo nl2br("Fo.\nPro.");
?>
Result
Fo.
Pro.
the html element break line depend of it's white-space style property.
in the most of the elements the default white-space is auto, which mean break line when the text come to the width of the element.
if you want the text break by \n you have to give to the parent element the style:
white space: pre-line, which will read the \n and break the line, or
white-space: pre which will also read \t etc.
note: to write \n as break-line and not as a string , you have to use a double quoted string ("\n")
if you not wanna use a white space, you always welcome to use the HTML Element for break line, which is <br/>
$a = 'John' ; <br/>
$b = 'Doe' ; <br/>
$c = $a.$b"<br/>";

What good is new line character?

I don't really get it: what's the purpose of a new line character?
If I do this:
<?php
echo "This is a test. \n";
echo "This is another test.";
?>
Code results in both sentences being in the same line. Why doesn't the \n causes the second sentence being in second line?
The sentences are each in it's own line, if I do:
<?php
echo "This is a test. <br>";
echo "This is another test.";
?>
But I have also seen people do this:
<?php
echo "This is a test. <br>\n";
echo "This is another test.";
?>
Which essentially results in the same output as the second code snippet. Someone care to explain this?
The HTML standard treats a line break as just another white space character, which is why the <br> tag exists. Note however a line break will work within a <pre> tag, or an element with the white-space:pre CSS style.
The third example is just to make "pretty" HTML: it makes it easier to "view source" and check it by eye. Otherwise, you have a big long string of HTML.
as you have observed there are different ways to create a new line.
<br />
this is not a new line character, this is an XHTML tag which means, it works in XHTML.
correctly speaking it is not a new line character but the tag makes sure, one is inserted = it forces a line break. closing tag is mandatory.
XHTML specs
<br>
this is a HTML tag which forces a line break. closing tag is prohibited.
HTML 4.1 specs
\n
is an escape sequence for the ASCII new line char LF. A common problem is the use of '\n' when communicating using an Internet protocol that mandates the use of ASCII CR+LF for ending lines. Writing '\n' to a text mode stream works correctly on Windows systems, but produces only LF on Unix, and something completely different on more exotic systems. Using "\r\n" in binary mode is slightly better, as it works on many ASCII-compatible systems, but still fails in the general case. One approach is to use binary mode and specify the numeric values of the control sequence directly, "\x0D\x0A".
read more
PHP_EOL
is a php new line constant which is replaced by the correct system dependent new line.
so the message is, use everything in it's right place.
<br> will give you a new line in the user's view; \n will give you a new line in source code, ie. developer's view.
When the html is rendered, only the "<br />" renders the break line. However the markup is much easier to read when "<br />\n" is printed, so that everything is not in one long line.
\n is code based
<br /> is HTML tag based
There is a clear distinction between the two.
Your problem is the way html is rendered. If you look in the source code, the first example will have the two lines on separate lines, but the browser does not see line breaks as breaks that should be displayed. This allows you to have a long paragraph in your source:
rghruio grgo rhgior hiorghrg hg rgui
ghergh ugi rguihg rug hughuigharug
hruauruig huilugil guiui rui ghruf hf
uhrguihgui rhguibuihfioefhw8u
beruvbweuilweru gwui rgior
That would only wrap as the browser needed it to, allowing it to be easily editable at the right line length, but displayed at any resolution.
HTML does not care about new lines in the source code, you can put it all in one line. It will only interpret <br /> as a new line. You should use an \n to beautify your HTML-output though, but the better way is to not output it with PHP, but to use it in the HTML itself and only embed PHP stuff into it, like this:
<ul id="menu">
<?php foreach ($menu_items as $item): ?>
<li>
<a href="<?= htmlspecialchars($item['link']) ?>" title="<?= htmlspecialchars($item['title']) ?>">
<?= htmlspecialchars($item['title']) ?>
</a>
</li>
<?php endforeach; ?>
</ul>
That way you won't have to bother with formatting inside PHP, but you automagically have it, by design, in HTML. Also, you seperate Model-logic and View-logic from each other like this and leave the output to your HTTP Server rather than the PHP engine.
That's because you're creating HTML and view it in a browser, and whitespace is more or less ignored there. Ten spaces don't produce a bigger gap than one space, but that doesn't mean that the space character doesn't work. Try setting the content type to text/plain or look at the HTMLs source to see the effect of the newline.
The correct XHTML syntax for it would be
echo "This is the test code <br />\n";
The <br /> renders a new line onscreen, the "\n" renders a new line in the source coed
The new line character is useful otherwise, such as in a PDF. You're correct that the new line character has very little do with HTML as other people have said, it's treated as another while space character. Although it is useful inside the <pre> tag. It can also be used to format the HTML output to make it easier to read. (It's a little annoying to try to find a piece of HTML in a string that's 1000 characters wide.)
The new line character is also useful when storing data in the database. Usually you want to store the data without HTML special characters such as <br /> so that it can be easily used in other formats (again, such as PDF). On output, you want to use the nl2br() function to convert the new lines to <br />s.
The new line character is is useful for string functions.
For example:
explode( '\n' , $input );
Would split a string by a new line.
str_replace( '\n' , '<br />' , $input );
Would replace every newline in $input with a br tag.
Also because PHP also has a CLI, \n is useful for formatting:
eg.
echo 'Hello world';
Would, in the CLI, output;
Hello worldphp>
echo 'Hello world' . "\n";
would output;
Hello world
php>
Although it also has uses when writing web-based scripts, keep in mind PHP is more than a web engine; it also has a CLI where the br tag is useless.
<br /> is also useless if you're running a script from the command line.
$ php -f file.php
Output <br />$
I know not too many people use PHP from the command line, but it does come up:
file.php:
<?php
print "Output\n";
?>
At the command line:
$ php -f file.php
Output
$

Categories