What are some best practices for handling data output in text fields in PHP?

When outputting data in text fields in PHP, it is important to properly sanitize and escape the data to prevent any potential security vulnerabilities such as SQL injection or cross-site scripting attacks. One common approach is to use the htmlspecialchars() function to encode special characters in the output.

<?php
// Assuming $data contains the data to be outputted in a text field
$data = "<script>alert('XSS attack');</script>";

// Sanitize and output the data in a text field
echo '<input type="text" value="' . htmlspecialchars($data) . '">';
?>