simple problem baffling me...
i have a function:
function spitHTML() {
$html = '
<div>This is my title</div>\n
<div>This is a second div</div>';
return $html
}
echo $spitHTML();
Why is this actually spitting out the \n's?
simple problem baffling me...
i have a function:
function spitHTML() {
$html = '
<div>This is my title</div>\n
<div>This is a second div</div>';
return $html
}
echo $spitHTML();
Why is this actually spitting out the \n's?
Change ' to " :) (After that, all special chars and variable be noticed)
$html = "
<div>This is my title</div>\n
<div>This is a second div</div>";
Because you're using single quotes - change to double quotes and it will behave as you expect.
See the documentation for Single quoted strings.
Backslashes used in single quote strings do not work as escape characters (besides for the single quote itself).
$string1 = "\n"; // this is a newline
$string2 = '\n'; // this is a backslash followed by the letter n
$string3 = '\''; // this is a single quote
$string3 = "\""; // this is a double quote
So why use single quotes at all? The answer is simple: If you want to print, for example, HTML code, in which naturally there are a lot of double quotes, wrapping the string in single quotes is much more readable:
$html = '<div class="heading" style="align: center" id="content">';
This is far better than
$html = "<div class=\"heading\" style=\"align: center\" id=\"content\">";
Besides that, since PHP doesn't have to parse the single quote strings for variables and/or escaped characters, it processes these strings a bit faster.
Personally, I always use single quotes and attach newline characters from double quotes. This then looks like
$text = 'This is a standard text with non-processed $vars followed by a newline' . "\n";
But that's just a matter of taste :o)