How can PHP developers effectively filter out HTML and JavaScript from user input to prevent security vulnerabilities?

To effectively filter out HTML and JavaScript from user input in PHP, developers can use the `htmlspecialchars` function to convert special characters to HTML entities. This helps prevent cross-site scripting (XSS) attacks by rendering any potentially harmful code as plain text.

$user_input = "<script>alert('XSS attack!');</script>";
$filtered_input = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
echo $filtered_input;