I was in need of $dom->getElementsByTagName that would hist magic within a contextNode.
Why i needed getElementsByTagName instead of just simple using an xPath->query is because while looping through the returned nodelist, more nodes with the tagName i was looking for where created.
When using getElementsByTagName, the new nodes are "added" to the nodelist i already am looping through.
When using an xpath query, you wil only loop through the original nodelist, the newly created elements wil not appear in that nodelist.
I was already using an extended class on domDocument, so it was simple to create an kind of getElementsByTagName that would accept an contextNode.
<?php
class SmartDocument extends DOMDocument {
private $localDom;
public $xpath;
private $serialize = array('localDom');
private $elemName;
private $elemCounter;
/**
* Constructor
*/
function __construct() {
parent::__construct ( '1.0', 'UTF-8' );
$this->preserveWhiteSpace = false;
$this->recover = TRUE;
$this->xpath = new DOMXpath ( $this );
}
/**
* GetElementsByTagname within an contextNode
*
* @param string $name
* @param DomNode $contextNode
* @return DOMNode|NULL
*/
public function getElementsByTagNameContext($name, $contextNode) {
if($this->elemName!=$name) {
$this->elemCounter = 0;
$this->elemName =$name;
}
$this->elemLength = $this->xpath->evaluate('count(.//*[name()="'.$this->elemName.'"])', $contextNode);
while($this->elemCounter < $this->elemLength) {
$this->elemCounter++;
$nl = $this->xpath->query('.//*[name()="'.$this->elemName.'"]['.$this->elemCounter.']', $contextNode);
if($nl->length == 1) {
return $nl->item(0);
}
}
$this->elemLength = null;
$this->elemCounter = null;
$this->elemName = null;
return null;
}
}
?>
Usage:
<?php
$doc = new SmartDocument();
$doc->load('book.xml');
$nl = $doc->query('//books');
foreach($nl as $node) {
while($book = $doc->getElementsByTagNameContext('book', $node)) {
//When you now create new nodes within this loop as child or following-sibling of this node
// They show up within this loop
}
}
?>