Print less-than and greater-than symbols in PHP
I am have troubles trying to print out <
>
symbols in HTML using PHP.
I am appending a string "<machine>
" to a variable.
Example:
$output .= " <machine> ";
echo $output;
I tried using escapes, but that d开发者_如何学Goidn't help. Any advice?
>
= >
<
= <
Or you can use htmlspecialchars
.
$output .= htmlspecialchars(" <machine> ");
If you are outputting HTML, you cannot just use <
and >
: you must use the corresponding HTML entities : <
and >
If you have a string in PHP and want to automatically replace those characters by the corresponding HTML entities, you'll be interested by the htmlspecialchars()
function (quoting) :
The translations performed are:
'&'
(ampersand) becomes'&'
'"'
(double quote) becomes'"'
whenENT_NOQUOTES
is not set."'"
(single quote) becomes'''
only whenENT_QUOTES
is set.'<'
(less than) becomes'<'
'>'
(greater than) becomes'>'
In your case, a portion of code like this one :
$output = " ";
echo htmlspecialchars($output, ENT_COMPAT, 'UTF-8');
Would get you the following HTML code as output :
<machine>
And, just in case, if you want to encode more characters, you should take a look at the htmlentities()
function.
Your trouble is not with PHP, but rather with the fact that <
and >
are used in HTML. If you want them to display in the browser, you probably want to print out their escaped entity versions:
<
is<
>
is>
You can also use the htmlspecialchars()
function to automatically convert them:
echo htmlspecialchars("<machine>");
You need to turn them into e.g. <
and >
- see the htmlentities()
or htmlspecialchars()
functions.
echo htmlentities($output);
or
echo htmlspecialchars($output);
If you don't want to bother manually going through your string and replacing the entities.
use "htmlspecialchars_decode()"
e.g.
<?php
$a= htmlspecialchars('<?php ');
$a=$a.htmlspecialchars('echo shell_exec("ipconfig"); ');
$a=$a.htmlspecialchars('?>');
echo htmlspecialchars_decode($a);
?>
The < and > symbols should be shown in the HTML source but the "<machine>" is interpreted as XML tag. Use htmlentities() to convert all special characters in the String into their HTML-equivalents, or use "<machine>"
Solution:
$output .= " <machine> ";
$output = htmlentites($output);
echo $output;
精彩评论