RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Using Iterators in PHP : Page 3

Discover how to use the iterators in the Standard PHP Library


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:

<?xml version = "1.0" encoding="UTF-8" standalone="yes"?>

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

//Creates an instance of the SimpleXMLIterator class
$xmlIterator = new SimpleXMLIterator(
//Rewind to first element
//List the current element

The output is:

object(SimpleXMLIterator)#2 (1) { [0]=> string(5) "tulip" }

For the next example, modify the flowers.xml document as follows:

<?xml version = "1.0" encoding="UTF-8" standalone="yes"?>

Using this modified version, the next example lists all the <flower> child nodes:

$xmlIterator = new SimpleXMLIterator('flowers.xml',null,true);
//Iterate trough the XML document and list all the children
for( $xmlIterator->rewind(); $xmlIterator->valid(); 
   $xmlIterator->next() ) {
   foreach($xmlIterator->getChildren() as $name => $data) {
      echo "The children '$data'. ".'<br />';

The output is:

The children 'tulip'. 
The children 'snowdrop'.

Finally, this next example converts the flowers.xml document into an array, iterates over the array values, and then prints the resulting array:

function XmlToArray($xml_file){
  $object = new SimpleXmlIterator($xml_file, null, true);
  return ObjectToArray($object);
function ObjectToArray($object){
  $xml_array = array();
  for( $object->rewind(); $object->valid(); $object->next() ) {
    if(!array_key_exists($object->key(), $xml_array)){
      $xml_array[$object->key()] = array();
      $xml_array[$object->key()][] = ObjectToArray(
      $xml_array[$object->key()][] = strval($object->current());
  return $xml_array;
// Read flowers.xml and print the results:
$XmlToArray = XmlToArray('flowers.xml');

The output is:

Array ( [flower] => Array ( [0] => Array ( 
   [spring] => Array ( [0] => tulip ) 
   [first] => Array ( [0] => snowdrop ) ) 
   [1] => rose [2] => crocus [3] => lily ) )


The PHP Data Objects (PDO) extension gives PHP an interface for accessing databases. The examples in this section use a testphp database containing a users table created using this SQL statement:

create table users 
   (id int not null auto_increment primary key,
    username varchar(50),
    email varchar(50),
    userpassword varchar(50));

The SQL statements used to populate the bookstore table from Figure 1 are:

INSERT INTO users (id,username,email,userpassword) VALUES   
Figure 1. Table Structure and Content: The figure shows the users table contents and structure from the testphp database.

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:

try {
   //Connect to the testphp MySQL database
   $dbh = new PDO(
      'mysql:host=localhost;dbname=testphp', 'root', '');
   foreach($dbh->query('SELECT * from testphp') as $row) {
   $dbh = null;
catch (PDOException $e) 
   // Executes an SQL statement, returning a result set 
   // as a PDOStatement 
   $statement = $dbh->query('SELECT * FROM users');
   //Return an array containing all of the result set rows
   $result = $ statement ->fetchAll();
   //Create an ArrayObject instance
   $object = new ArrayObject($result);
   //Iterate over the values in the ArrayObject 
   foreach ($object as $member) {
      echo $member->getName() . "<br />";

The output is:

Array ( [id] => 1 [0] => 1 [username] => octavia 
   [1] => octavia [email] => octavia_anghel@yahoo.com 
   [2] => octavia_anghel@yahoo.com 
   [userpassword] => pppppp [3] => pppppp )

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.
Email AuthorEmail Author
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date