Skip to Main Content
Upgrading to PHP 5
book

Upgrading to PHP 5

by Adam Trachtenberg
July 2004
Intermediate to advanced content levelIntermediate to advanced
350 pages
10h 9m
English
O'Reilly Media, Inc.
Content preview from Upgrading to PHP 5

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.
Start your free trial

You might also like

Expert PHP and MySQL®

Expert PHP and MySQL®

Andrew Curioso, Ronald Bradford, Patrick Galbraith
Pro PHP Programming

Pro PHP Programming

Peter MacIntyre, Brian Danchilla, Mladen Gogala
Mastering PHP 7

Mastering PHP 7

Branko Ajzele

Publisher Resources

ISBN: 0596006365Supplemental ContentCatalog PageErrata