SimpleXML Iterator
The SimpleXML iterator allows you to use SimpleXML objects with the other iterator classes. This allows you to easily construct an SQL-like interface to XML files.
For instance, suppose you have an XML address book like the one in Example 5-1. However, instead of containing only 2 records, it contains hundreds of records, and you want to display the records in groups of 10.
One solution is to place the information into a database. Another is
to use XPath. A third is to combine a
SimpleXMLIterator with a
LimitIterator:
$ab = file_get_contents('address-book.xml');
$page = 0;
$limit = 10;
foreach (new LimitIterator(new SimpleXMLIterator($ab),
$page * $limit, $limit) as $person) {
print "$person->firstname $person->lastname: $person->email\n";
}The SimpleXMLIterator takes a string of XML and
creates an iterable SimpleXML object. Here, it’s
parsing address-book.xml.
This iterator is then passed to a LimitIterator
that restricts the output to only the $limit
number of records beginning at $page * $limit.
When $page is 0, it returns the
first 10 records; when $page is
1, you get records 11 through 20.
The $person item can be treated like a
SimpleXMLElement, so
$person->firstname returns the text stored in
the firstname element.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access