What is the significance of escaping characters within HTML attributes in PHP?

Escaping characters within HTML attributes in PHP is important to prevent security vulnerabilities such as cross-site scripting (XSS) attacks. By escaping characters, we ensure that user input is properly sanitized before being outputted to the HTML attributes, thus preventing malicious code from being executed.

<?php
$user_input = '<script>alert("XSS attack")</script>';
$escaped_input = htmlspecialchars($user_input, ENT_QUOTES);
echo '<input type="text" value="' . $escaped_input . '">';
?>