Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I use XPath and DOM to replace a node/element in php?
    text
    copied!<p>Say I have the following html</p> <pre><code>$html = ' &lt;div class="website"&gt; &lt;div&gt; &lt;div id="old_div"&gt; &lt;p&gt;some text&lt;/p&gt; &lt;p&gt;some text&lt;/p&gt; &lt;p&gt;some text&lt;/p&gt; &lt;p&gt;some text&lt;/p&gt; &lt;div class="a class"&gt; &lt;p&gt;some text&lt;/p&gt; &lt;p&gt;some text&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="another_div"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; '; </code></pre> <p>And I want to replace <code>#old_div</code> with the following:</p> <pre><code>$replacement = '&lt;div id="new_div"&gt;this is new&lt;/div&gt;'; </code></pre> <p>To give an end result of:</p> <pre><code>$html = ' &lt;div class="website"&gt; &lt;div&gt; &lt;div id="new_div"&gt;this is new&lt;/div&gt; &lt;div id="another_div"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; '; </code></pre> <p>Is there an easy cut-and-paste function for doing this with PHP?</p> <hr> <p><strong>Final working code thanks to all Gordon's help:</strong></p> <pre><code>&lt;?php $html = &lt;&lt;&lt; HTML &lt;div class="website"&gt; &lt;div&gt; &lt;div id="old_div"&gt; &lt;p&gt;some text&lt;/p&gt; &lt;p&gt;some text&lt;/p&gt; &lt;p&gt;some text&lt;/p&gt; &lt;p&gt;some text&lt;/p&gt; &lt;div class="a class"&gt; &lt;p&gt;some text&lt;/p&gt; &lt;p&gt;some text&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="another_div"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; HTML; $dom = new DOMDocument; $dom-&gt;loadXml($html); // use loadHTML if it's invalid XHTML //create replacement $replacement = $dom-&gt;createDocumentFragment(); $replacement -&gt;appendXML('&lt;div id="new_div"&gt;this is new&lt;/div&gt;'); //make replacement $xp = new DOMXPath($dom); $oldNode = $xp-&gt;query('//div[@id="old_div"]')-&gt;item(0); $oldNode-&gt;parentNode-&gt;replaceChild($replacement , $oldNode); //save html output $new_html = $dom-&gt;saveXml($dom-&gt;documentElement); echo $new_html; ?&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