Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^158) CHAPTER 10 ■ SPL ITERATORS
RecursiveRegexIterator
The RecursiveRegexIterator is the recursive form of the RegexIterator. It has the same usage
as RegexIterator, except that it must be given a RecursiveIterator to iterate.
RecursiveDualIterator
The RecursiveDualIterator allows you to concurrently iterate two RecursiveIterator iterators. It
has the same basic usage as DualIterator. Once you obtain a left-hand or right-hand side iterator,
you should call getInnerIterator().
RecursiveCachingIterator
The RecursiveCachingIterator performs one-ahead recursion on a RecursiveIterator and
can be extremely useful for allowing you to determine if the current iterator entry is a leaf or a
node.
SearchIterator
The SearchIterator iterator performs both a filter and a limit, and stops after it finds a matching
element. It is presented as an abstract class, and you must implement accept(), just as with
any other FilterIterator.


Real-World Iterator Implementations


At times, iterators can seem like an academic topic; however, they have many practical uses. As
a PHP developer, you will find them in increasing frequency in nearly all your favorite PHP
applications and frameworks. The following are some concrete examples that you may find
useful in your applications.

Parsing XML with SimpleXML.


The SimpleXML extension introduced in PHP 5 is a really efficient and easy way to access data
in the XML format. It’s not suitable for all applications, and it has its limitations. However, if
you just need to read the structure, the SimpleXML iterator will make working with XML in PHP
truly a pleasure.
SimpleXML is enabled by default and won’t require any reconfiguration of PHP. To use
the SimpleXML iterator, you will need to create a sample XML file, such as the one shown in
Listing 10-16.

Listing 10-16. A Sample XML File (test.xml)

<library>
<book>
<name>Pro PHP</name>
<author>Kevin McArthur</author>
</book>

McArthur_819-9C10.fm Page 158 Friday, February 22, 2008 9:08 AM

Free download pdf