Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Since the answer in the linked duplicate is not that comprehensive, I'll give an example:</p> <pre><code>$dom = new DOMDocument; $dom-&gt;loadXml($html); // use loadHTML if its invalid (X)HTML // create the new element $newNode = $dom-&gt;createElement('div', 'this is new'); $newNode-&gt;setAttribute('id', 'new_div'); // fetch and replace the old element $oldNode = $dom-&gt;getElementById('old_div'); $oldNode-&gt;parentNode-&gt;replaceChild($newNode, $oldNode); // print xml echo $dom-&gt;saveXml($dom-&gt;documentElement); </code></pre> <hr> <p>Technically, you don't need XPath for this. However, it can happen that your version of libxml cannot do <code>getElementById</code> for non-validated documents (<a href="http://www.w3.org/TR/2005/REC-xml-id-20050909/REC-xml-id-20050909.xml" rel="noreferrer">id attributes are special in XML</a>). In that case, replace the call to <code>getElementById</code> with</p> <pre><code>$xp = new DOMXPath($dom); $oldNode = $xp-&gt;query('//div[@id="old_div"]')-&gt;item(0); </code></pre> <p><a href="http://codepad.org/EJ8e6QYk" rel="noreferrer">Demo on codepad</a></p> <hr> <p>To create a <code>$newNode</code> with child nodes without having to to create and append elements one by one, you can do</p> <pre><code>$newNode = $dom-&gt;createDocumentFragment(); $newNode-&gt;appendXML(' &lt;div id="new_div"&gt; &lt;p&gt;some other text&lt;/p&gt; &lt;p&gt;some other text&lt;/p&gt; &lt;p&gt;some other text&lt;/p&gt; &lt;p&gt;some other text&lt;/p&gt; &lt;/div&gt; '); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload