How can PHP developers ensure that user input containing HTML tags is safely displayed without risking cross-site scripting vulnerabilities?

To safely display user input containing HTML tags without risking cross-site scripting vulnerabilities, PHP developers can use the `htmlspecialchars()` function to encode the user input before displaying it on the webpage. This function will convert special characters like `<`, `>`, `&`, and `"` into their HTML entities, preventing the browser from interpreting them as actual HTML tags.

$userInput = &quot;&lt;script&gt;alert(&#039;XSS attack!&#039;);&lt;/script&gt;&quot;;
$safeInput = htmlspecialchars($userInput, ENT_QUOTES);
echo $safeInput;