How to convert a PHP DOMElement into a PHP DOMNodeList

668 views Asked by At

I have a situation where I have a little function like below...

public function childUpdate($nodes, $newValue) {
    //Update values of each node
    foreach ($nodes as $child) {
        $child->nodeValue = $newValue;
    }
}

This works perfectly whenever my function is sent a DOMNodeList but occasionally it can be sent a DOMElement instead.

This is a problem as in that situation, the foreach ($nodes as $child) { line fails as foreach does not work on a single element, and requires a list.

So my question is -- is there an elegant way to quickly convert a DOMElement into a DOMNodeList with just that one element inside it?

The obvious first thought is to wrap the DOMElement inside an array like array(DOMElement), and while that works for this function above, it does fail in other situations where I rely on DOMNodeList specific features.

A simple way to convert DOMElement into a DOMNodeList would really simplify my code and remove a lot of "if 'element' do this, this 'list' do that" conditions.

2

There are 2 answers

0
Ben Michelson On

If you have a DOMXPath for the document, you can use

 $nodeList = $xpath->query(".", $node);
0
Paul B On

Having the same problem.

With advice from: How to add elements to DOMNodeList in PHP?

Create a DOMDocument, add the DOMElement to it, and get childNodes which is a DOMNodeList

if(!property_exists($data,'length')) {
  $doc = new DOMDocument();
  $elem = $doc->importNode($data);
  $doc->appendChild($elem);
  $nodeList = $doc->childNodes;
}