PHP provides two useful functions, htmlentities() and htmlspecialchars(), that convert special characters into HTML entities. These functions are essential for preventing HTML injection and XSS attacks while ensuring text is displayed safely.
htmlentities() converts all applicable characters to HTML entities.htmlspecialchars() converts only the most common special characters like <, >, and &.htmlentities(string) encodes every special character.htmlspecialchars(string) encodes only essential characters for HTML safety.
// Converts all special characters into HTML entities
<?php
$string = "This is a <b>bold</b> statement!";
$encoded = htmlentities($string);
echo $encoded;
?>
All HTML tags are converted into entity form, ensuring the browser displays them as plain text instead of executing them.
// Escapes only critical HTML characters for safe rendering
<?php
$string = "This is a <b>bold</b> statement!";
$encoded = htmlspecialchars($string);
echo $encoded;
?>
Only critical characters are escaped, making this function ideal for safely displaying HTML code without breaking layout.
htmlspecialchars() for most user input scenarioshtmlentities() for strict encoding needs