Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 10 ■ SPL ITERATORS^159

<book>
<name>Other Book</name>
</book>
</library>

The SimpleXMLIterator is a RecursiveIterator that allows you to access all the nodes within
an XML document. The example in Listing 10-17 uses the recursive nature of the iterator to
create a listing of books and their elements in the test.xml file.

Listing 10-17. Using the SimpleXML Iterator

$it = new SimpleXMLIterator(file_get_contents('test.xml'));

foreach($it as $key=>$node) {
echo $key. "\n";
if($it->hasChildren()) {
foreach($it->getChildren() as $element=>$value) {
echo "\t". $element. ":". $value ."\n";
}
}
}

book
name:Pro PHP
author:Kevin McArthur
book
name:Other Book

The hasChildren() condition is not required, but is included for demonstration. Without
hasChildren(), getChildren() will simply return no elements and the foreach loop would not
be entered.

Accessing Flat-File Databases with DBA


The DBA extension provides access to many useful flat-file format databases, like the popular
DB4 format. The DBA iterators are useful for accessing data exposed by the DBA extension. The
following examples use the .ini file handler, but several other handlers are available. To build
PHP with the DBA extension with .ini file and cdb drivers enabled, you must include the
following in your PHP configure line:

--enable-dba --with-inifile

■Note Many package-managed installations of PHP will include some support for DBA. Its presence, as
well as the existence of specific drivers, is exposed via phpinfo().

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

Free download pdf