What are some best practices for handling HTML entities in PHP functions?

When working with HTML entities in PHP functions, it is important to properly handle encoding and decoding to prevent security vulnerabilities such as cross-site scripting (XSS) attacks. To ensure safe handling of HTML entities, use functions like htmlspecialchars() to encode special characters in output and htmlentities() to decode HTML entities in input.

// Encoding HTML entities in output
$text = "<script>alert('XSS attack');</script>";
echo htmlspecialchars($text, ENT_QUOTES, 'UTF-8');

// Decoding HTML entities in input
$input = "<script>alert('XSS attack');</script>";
echo htmlentities($input, ENT_QUOTES, 'UTF-8');