What are some best practices for handling text formatting and output in PHP forms to ensure proper display on webpages?

When handling text formatting and output in PHP forms, it is important to sanitize user input to prevent malicious code injection and ensure proper display on webpages. One best practice is to use functions like htmlspecialchars() to encode special characters before displaying user input on a webpage.

// Sanitize user input before displaying on webpage
$userInput = "<script>alert('XSS attack!');</script>";
$sanitizedInput = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');

echo $sanitizedInput;