How can htmlspecialchars be used effectively to prevent HTML injection in PHP?

To prevent HTML injection in PHP, htmlspecialchars function can be used effectively. This function converts special characters in a string to HTML entities, which prevents malicious code from being executed in the browser. By using htmlspecialchars on user input before displaying it on a webpage, you can protect against cross-site scripting attacks.

$user_input = "<script>alert('Hello');</script>";
$escaped_input = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
echo $escaped_input;