6.5 SimpleXML Iterator

 <  Day Day Up  >  

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 , 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.

 <  Day Day Up  >  


Upgrading to PHP 5
Upgrading to PHP 5
ISBN: 0596006365
EAN: 2147483647
Year: 2004
Pages: 144

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net