How can one ensure proper formatting and escaping of data in PHP output?

Improper formatting and escaping of data in PHP output can lead to security vulnerabilities such as SQL injection or cross-site scripting attacks. To ensure proper formatting and escaping, use functions like htmlentities() or htmlspecialchars() to encode special characters in the output data. Additionally, always validate and sanitize user input before displaying it to prevent any malicious code execution.

// Example of ensuring proper formatting and escaping of data in PHP output
$user_input = "<script>alert('XSS attack!');</script>";

// Using htmlspecialchars to escape special characters
$escaped_input = htmlspecialchars($user_input);

// Output the properly escaped data
echo $escaped_input;