How can the htmlentities() function be utilized to prevent HTML code from being processed in PHP output?

To prevent HTML code from being processed in PHP output, the htmlentities() function can be used to convert special characters to HTML entities. This ensures that any HTML tags within the output are displayed as plain text rather than being interpreted as markup. By using htmlentities(), you can prevent potential security vulnerabilities such as cross-site scripting (XSS) attacks.

<?php
$output = "<script>alert('XSS attack!');</script>";
echo htmlentities($output);
?>