I am trying to use 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 "
";
echo $selected_val; // Displaying Selected Value
}
When writing PHP code, you need to distinguish between two distinct concepts :
" "
<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 " "
and <br />
:
echo "<br />
";
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>
" . $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.
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 " ";
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' . "
" . 'another line';
echo nl2br($string);
On echo, use <br />
.
The 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.