Reputation: 266
I am trying to use \n
in PHP to get a new line on my website, but it's not working.
Here is my code:
if(isset($_POST['selected'])){
$selected_val = $_POST['selected'];
// Storing Selected Value In Variable
echo "\n";
echo $selected_val; // Displaying Selected Value
}
Upvotes: 2
Views: 4832
Reputation: 3351
This essentially boils down to saving the below text to a HTML file and expecting it to have visual line breaks:
one line
another line
To have a visual line break in HTML you're gonna need the br
element:
one line<br />
another line
So replace your echo "\n";
with echo '<br />';
.
If you have a string containing newlines, you could use the php built in nl2br
to do the work for you:
<?php
$string = 'one line' . "\n" . 'another line';
echo nl2br($string);
Upvotes: 3
Reputation: 47101
When writing PHP code, you need to distinguish between two distinct concepts :
"\n"
<br />
So, Option 1 makes you go to the new line in the code you produce, but you will not go to a new line in the HTML webpage you produce. The same way, option 2 makes you go to the new line in the HTML webpage you produce, but you will not go to a new line in the code you produce.
If you want go to the next line in both your code and the HTML output, you can just combine "\n"
and <br />
:
echo "<br />\n";
Upvotes: 2
Reputation: 584
On a web page, out of a <pre>
block, all occurrences of tabs and newlines characters are assimilated as a single space.
For example:
echo "<pre>\n" . $selected_val . "</pre>";
But if your code is for debugging purposes, you'd better use print_r
to inspect your variable values. Such as:
echo "<pre>" . htmlspecialchars(print_r($select_val), true) . "</pre>";
The htmlspecialchars
function preserving you from ill-formed HTML due to the variable content.
Upvotes: 0
Reputation: 408
On echo, use <br />
.
The \n
won't work in the HTML page, only in the source code, executing the PHP from the command line or writing into a text file.
Upvotes: 3