How can special characters like "<" be properly encoded in PHP to avoid unexpected output?

Special characters like "<" can be properly encoded in PHP using the htmlspecialchars() function. This function converts special characters to their HTML entities, preventing them from being interpreted as code and causing unexpected output on the webpage.

$text = &quot;&lt;h1&gt;Hello, World!&lt;/h1&gt;&quot;;
echo htmlspecialchars($text);