How can htmlentities() be used to prevent special characters from being displayed incorrectly in PHP?

Special characters can be displayed incorrectly in PHP when they are not properly encoded. The htmlentities() function can be used to convert special characters to HTML entities, preventing them from being interpreted as code and ensuring they are displayed correctly on the webpage.

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