Reputation: 3388
I would like to know whether in PHP 5.6.11 there is any difference between the following two ways of iterating with SimpleXMLElement:
$simpleXMLIterator = new SimpleXMLIterator($xmlCode);
foreach ($simpleXMLIterator as $xmlElement) {
echo $xmlElement->getName(), "\n";
}
and
$simpleXMLIterator = new SimpleXMLIterator($xmlCode);
for ($simpleXMLIterator->rewind(); $simpleXMLIterator->valid(); $simpleXMLIterator->next()) {
echo $simpleXMLIterator->current()->getName(), "\n";
}
Upvotes: 1
Views: 186
Reputation: 19502
It will call the same logic inside the object. Iterator
is an interface that you can implement into your own objects. The interface specifies methods like rewind()
, next()
, current()
, ...
If you implement the interface the object can be used with foreach()
. foreach()
recognizes the interface and calls the methods.
SimpleXMLIterator
implements that interface, more specific it implements RecursiveIterator
which extends Iterator
with two methods (hasChildren()
and getChildren()
to handle recursive structures.
Upvotes: 1