What are the recommended functions in PHP to handle HTML escaping and decoding to prevent display problems?

To prevent display problems such as cross-site scripting (XSS) attacks, it is recommended to escape HTML characters before displaying user input on a webpage. PHP provides functions like htmlspecialchars() to encode special characters in HTML entities and prevent them from being interpreted as code. Similarly, the html_entity_decode() function can be used to decode HTML entities back to their original characters.

// Encoding HTML entities to prevent XSS attacks
$user_input = "<script>alert('XSS attack!');</script>";
$escaped_input = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');

echo $escaped_input;

// Decoding HTML entities
$encoded_string = "<script>alert('XSS attack!');</script>";
$decoded_string = html_entity_decode($encoded_string, ENT_QUOTES, 'UTF-8');

echo $decoded_string;