Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing DOMXPath to replace a node while maintaining its position
    primarykey
    data
    text
    <p>Ok, so I had this neat little idea the other night to create a helper class for DOMDOCUMENT that mimics, to some extent, jQuery's ability to manipulate the DOM of an HTML or XML-based string. Instead of css selectors, XPath is used. For example:</p> <pre><code>$Xml-&gt;load($source) -&gt;path('//root/items') -&gt;each(function($Context) { echo $Context-&gt;nodeValue; }); </code></pre> <p>This would invoke a callback function on every resulting node. Unfortunately, PHP version &lt; 5.3.x doesn't support lambda functions or closures, so I'm forced to do something a bit more like this for the time being:</p> <pre><code>$Xml-&gt;load($source) -&gt;path('//root/items') -&gt;walk('printValue', 'param1', 'param2'); </code></pre> <p>Everything is working great at the moment and I think this project would be useful to a lot of people, but I'm stuck with one of the functions. I am attempting to mimic jQuery's 'replace' method. Using the following code, I can accomplish this quite easily by applying the following method:</p> <pre><code>$Xml-&gt;load($source) -&gt;path('//root/items') -&gt;replace($Xml-&gt;createElement('foo', 'bar')); // can be an object, string or XPath pattern </code></pre> <p>The code behind this method is:</p> <pre><code>public function replace($Content) { foreach($this-&gt;results as $Element) { $Element-&gt;parentNode-&gt;appendChild($Content-&gt;cloneNode(true)); $Element-&gt;parentNode-&gt;removeChild($Element); } return $this; } </code></pre> <p>Now, this works. It replaces every resulting element with a cloned version of $Content. The problem is that it adds them to the bottom of the parent node's list of children. The question is, how do I clone this element to replace other elements, while still retaining the original position in the DOM?</p> <p>I was thinking about reverse-engineering the node I was to replace. Basically, copying over values, attributes and element name from $Content, but I am unable to change the actual element name of the target element.</p> <p>Reflection could be a possibility, but there's gotta be an easier way to do this.</p> <p>Anybody?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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