How can the htmlentities function be used to ensure that HTML content within a PHP variable is displayed as text rather than rendered as HTML?

When HTML content is stored in a PHP variable and displayed on a webpage, it may be rendered as HTML code instead of plain text. To prevent this, the htmlentities function can be used to convert special characters in the HTML content to their corresponding HTML entities, ensuring that the content is displayed as text.

$html_content = "<h1>Hello, World!</h1>";
echo htmlentities($html_content);