In PHP, what is the recommended approach for handling special characters in HTML attributes to prevent syntax errors or security vulnerabilities?

Special characters in HTML attributes can cause syntax errors or security vulnerabilities if not properly handled. To prevent this, it is recommended to use the htmlspecialchars() function in PHP to encode special characters before outputting them in HTML attributes. This function will convert characters like <, >, ", ', and & into their respective HTML entities, ensuring that the output is safe and valid.

&lt;?php
$unsafe_input = &#039;&lt;script&gt;alert(&quot;XSS attack!&quot;)&lt;/script&gt;&#039;;
$safe_input = htmlspecialchars($unsafe_input, ENT_QUOTES, &#039;UTF-8&#039;);
echo &#039;&lt;input type=&quot;text&quot; value=&quot;&#039; . $safe_input . &#039;&quot;&gt;&#039;;
?&gt;