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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Using Iterators in PHP : Page 3

Discover how to use the iterators in the Standard PHP Library




Building the Right Environment to Support AI, Machine Learning and Deep Learning

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"?> <document> <flower>tulip</flower> <flower>rose</flower> <flower>crocus</flower> <flower>lily</flower> <flower>snowdrop</flower> </document>

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()); ?>

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"?> <document> <flower> <spring>tulip</spring> <first>snowdrop</first> </flower> <flower>rose</flower> <flower>crocus</flower> <flower>lily</flower> </document>

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

<?php $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:

<?php 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(); } if($object->hasChildren()){ $xml_array[$object->key()][] = ObjectToArray( $object->current()); } else{ $xml_array[$object->key()][] = strval($object->current()); } } return $xml_array; } // Read flowers.xml and print the results: $XmlToArray = XmlToArray('flowers.xml'); print_r($XmlToArray); ?>

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 (1,"octavia","octavia_anghel@yahoo.com","pppppp")

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:

<?php try { //Connect to the testphp MySQL database $dbh = new PDO( 'mysql:host=localhost;dbname=testphp', 'root', ''); foreach($dbh->query('SELECT * from testphp') as $row) { print_r($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.
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date