How To Output HTML Tags in PHP - htmlspecialchars() Function

PHP General Functions

If you need to display some HTML code on the browser, first you need to convert it into HTML entities. Otherwise, the code will be processed by the PHP. For example, instead of <bold> output, the text itself will become bold.

The htmlspecialchars() Function converts the predefined characters "<" (less than) and ">" (greater than) to HTML entities. The htmlspecialchars() function converts some predefined characters to HTML entities. The predefined characters are:

  • & (ampersand) becomes &amp;
  • " (double quote) becomes &quot;
  • ' (single quote) becomes &#039;
  • < (less than) becomes &lt;
  • > (greater than) becomes &gt;
$str = "This is <b>bold</b> text.";
echo htmlspecialchars($str);

The browser will display:

This is <b>bold</b> text.
Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive