What is the significance of properly escaping characters like < and > in PHP code and how can this be achieved?

Properly escaping characters like < and > in PHP code is important to prevent potential security vulnerabilities such as Cross-Site Scripting (XSS) attacks. This can be achieved by using the htmlspecialchars() function in PHP, which converts special characters like < and > into their HTML entity equivalents.

$unsafe_input = &quot;&lt;script&gt;alert(&#039;XSS attack!&#039;);&lt;/script&gt;&quot;;
$safe_input = htmlspecialchars($unsafe_input, ENT_QUOTES, &#039;UTF-8&#039;);
echo $safe_input;