Using Iterators in PHP : Page 3

Discover how to use the iterators in the Standard PHP Library

by Octavia Andreea Anghel

Oct 21, 2009

Page 3 of 3

The SimpleXMLIterator Class

The SimpleXMLIterator iterates recursively through all nodes of a SimpleXMLElement object. The examples in this section use the flowers.xml XML document available in the downloadable code, and listed below:

Here's an example that uses a SimpleXMLIterator to show the first element of the flowers.xml document.

<?php
//Creates an instance of the SimpleXMLIterator class
$xmlIterator = new SimpleXMLIterator(
'flowers.xml',null,true);
//Rewind to first element
$xmlIterator->rewind();
//List the current element
var_dump($xmlIterator->current());
?>

As an example, the following application connects to the testphp MySQL database using the PDO extension, executes a simple SELECT statement that returns the results as an array, and then iterates over the values:

In this article, you’ve seen how to implement iterators in your standard applications using the advanced array access, the file and directory access, and the SimpleXML object handling using the Standard PHP Library. Overall, I think you'll find iterators to be a highly useful addition to your PHP toolset.

Octavia Andreea Anghel is a senior PHP developer currently working as a primary trainer for programming teams that participate at national and international software-development contests. She consults on developing educational projects at a national level. She is a coauthor of the book "XML Technologies—XML in Java" (Albastra, ISBN 978-973-650-210-1), for which she wrote the XML portions. In addition to PHP and XML, she's interested in software architecture, web services, UML, and high-performance unit tests.