Skip to content

Instantly share code, notes, and snippets.

@macik
Last active November 29, 2019 06:57
Show Gist options
  • Save macik/10934587 to your computer and use it in GitHub Desktop.
Save macik/10934587 to your computer and use it in GitHub Desktop.
<?php
$dom = new DOMDocument; // create new DOMDocument instance
$dom->load('books.xml'); // load DOMDocument with XML data
$dit = new RecursiveIteratorIterator(
new RecursiveDOMIterator($dom),
RecursiveIteratorIterator::SELF_FIRST);
foreach($dit as $node) {
if($node->nodeType === XML_ELEMENT_NODE) {
echo $node->nodeName, PHP_EOL;
}
}
class RecursiveDOMIterator implements RecursiveIterator
{
/**
* Current Position in DOMNodeList
* @var Integer
*/
protected $_position;
/**
* The DOMNodeList with all children to iterate over
* @var DOMNodeList
*/
protected $_nodeList;
/**
* @param DOMNode $domNode
* @return void
*/
public function __construct(DOMNode $domNode)
{
$this->_position = 0;
$this->_nodeList = $domNode->childNodes;
}
/**
* Returns the current DOMNode
* @return DOMNode
*/
public function current()
{
return $this->_nodeList->item($this->_position);
}
/**
* Returns an iterator for the current iterator entry
* @return RecursiveDOMIterator
*/
public function getChildren()
{
return new self($this->current());
}
/**
* Returns if an iterator can be created for the current entry.
* @return Boolean
*/
public function hasChildren()
{
return $this->current()->hasChildNodes();
}
/**
* Returns the current position
* @return Integer
*/
public function key()
{
return $this->_position;
}
/**
* Moves the current position to the next element.
* @return void
*/
public function next()
{
$this->_position++;
}
/**
* Rewind the Iterator to the first element
* @return void
*/
public function rewind()
{
$this->_position = 0;
}
/**
* Checks if current position is valid
* @return Boolean
*/
public function valid()
{
return $this->_position < $this->_nodeList->length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment