Skip to content

Instantly share code, notes, and snippets.

@ryantenney
Created May 4, 2010 07:35
Show Gist options
  • Save ryantenney/389093 to your computer and use it in GitHub Desktop.
Save ryantenney/389093 to your computer and use it in GitHub Desktop.
<?php
/**
* DOMNodeListIterator
*
* Prior to PHP 5.3, DOMNodeList is not iterable. This solves that.
* Requires PHP SPL extension (for interface Iterator)
*
* Usage:
* $nodeIter = new DOMNodeListIterator($instanceOfClassDOMNodeList);
* foreach ($nodeIter as $node) { ... }
*
* Ryan W Tenney <ryan@10e.us>
*/
class DOMNodeListIterator implements Iterator {
private $pos = 0;
private $length;
private $nodelist;
public function __construct(DOMNodeList $nodelist) {
$this->nodelist = $nodelist;
$this->length = $nodelist->length;
}
public function rewind() {
$this->pos = 0;
}
public function current() {
return $this->pos < $this->length ? $this->nodelist->item($this->pos) : false;
}
public function key() {
return $this->pos;
}
public function next() {
++$this->pos;
return $this->current();
}
public function valid() {
return $this->pos < $this->length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment