What are the best practices for handling entities and escaping characters in PHP DOM manipulation?

When working with entities and special characters in PHP DOM manipulation, it is important to properly handle them to prevent security vulnerabilities like XSS attacks. To do this, use the `htmlspecialchars()` function to escape special characters before adding them to the DOM. This function will convert characters like <, >, ", ', and & into their respective HTML entities, ensuring they are displayed correctly and safely.

// Example of handling entities and escaping characters in PHP DOM manipulation
$dom = new DOMDocument();
$element = $dom-&gt;createElement(&#039;p&#039;, &#039;This is a &lt;span&gt;paragraph&lt;/span&gt; with special characters &amp; entities&#039;);
$escapedText = htmlspecialchars($element-&gt;nodeValue, ENT_QUOTES, &#039;UTF-8&#039;);
$element-&gt;nodeValue = $escapedText;

// Append the element to the DOM
$dom-&gt;appendChild($element);

// Output the HTML
echo $dom-&gt;saveHTML();