What are some best practices for securely displaying embedded code in PHP?

When displaying embedded code in PHP, it is important to properly escape any user input to prevent cross-site scripting attacks. One way to do this is by using the htmlspecialchars() function to convert special characters to HTML entities. Additionally, it is recommended to use a content security policy and validate user input to ensure that only safe and expected code is displayed.

<?php
// Example of securely displaying embedded code in PHP
$user_input = "<script>alert('XSS attack!');</script>";
$escaped_input = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
echo $escaped_input;
?>