18

I want to print following text as it is:

echo "<label> AAAAA";

But it is just showing 'AAAAA' as output.

How can I escape '<' and '>' symbol.

AnonGeek
  • 7,408
  • 11
  • 39
  • 55

8 Answers8

33

Use htmlspecialchars.

<?php
    echo htmlspecialchars("abc & < >");
?>
Oscar Broman
  • 1,109
  • 8
  • 19
  • It's annoying that the `htmlspecialchars` function is not succintly named. I wish PHP had an equivalent of ASP.NET's `<%: expr %>` or Razor's `@( expr )` which _automatically_ HTML-encodes the text to be rendered. In all of my PHP projects I alias `htmlentities( expr )` as `E( expr )` so I can have `= E( expr ) ?>`. Given PHP's "everything and the kitchen-sink" feature-set it's surprising it doesn't have an auto-encode feature or syntax built-in already. And correct HTML encoding is very important to prevent XSS attacks and should be encouraged. – Dai Jan 04 '20 at 19:03
6
<?php
    $string = "<label> AAAAA"; //whatever you want
    echo htmlspecialchars($string);
?>

refrence htmlspecialchars

itachi
  • 6,323
  • 3
  • 30
  • 40
5

Use the htmlentities() function to convert into a plain text string.

<?php
echo htmlentities("<label> AAAAA");
?>
0b10011
  • 18,397
  • 4
  • 65
  • 86
Userbn
  • 342
  • 1
  • 2
  • htmlentities is overkill. No need to bloat output by converting characters that are better represented with regular characters. – Quentin May 11 '12 at 12:17
  • 2
    The only time I'd consider `htmlentities` better than `htmlspecialchars` would be if the output is in a different charset than the code, which normally isn't the case. – Oscar Broman May 11 '12 at 12:20
5
echo htmlentities("<label> AAAAA");
Hadi Mostafapour
  • 1,994
  • 2
  • 13
  • 21
3

check this http://php.net/manual/en/function.htmlentities.php, and this is code -

echo htmlentities ("<label> AAAAA");
Tom
  • 4,612
  • 4
  • 32
  • 43
2

You should escape your especial characters for HTML.

echo "&lt;label&gt; AAAA"

http://www.w3schools.com/tags/ref_entities.asp

Enrique Paredes
  • 467
  • 3
  • 5
  • 1
    +1 for the right answer, but -1 for referring to w3schools. There are much better resources out there for learning this kind of stuff. (you may want to read http://w3fools.com/) – Spudley May 11 '12 at 18:24
0
echo "&lt;label&gt; AAAAA";
Rawkode
  • 21,990
  • 5
  • 38
  • 45
0

Use HTML entities: &lt; for < and &gt; for >. Could be achieved using htmlspecialchars function: http://php.net/htmlspecialchars.

Read more about HTML entities here: http://www.santagata.us/characters/CharacterEntities.html

shadyyx
  • 15,825
  • 6
  • 60
  • 95