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.
Get Upgrading to PHP 5 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.