Iterating Over XML with SimpleXMLIterator
Manipulating XML has been a notoriously difficult task, one which was greatly simplified with the introduction of PHP’s SimpleXML extension. The SimpleXMLIterator class builds upon the SimpleXML extension’s strengths, adding several new powerful capabilities to an already amazing feature. Consider the following Docbook-formatted file:
When using the date()
function, you must
provide at least one input parameter.
Suppose you wanted to parse this file in order to analyze the frequency in which code and glossary terms are referenced within the text. You can use the SimpleXMLIterator to easily examine the file:
<!--p
// Read the XML file into the SimpleXmlIterator object
$chapter = new SimpleXmlIterator('chapter.docbook', 0, TRUE);
// Iterate over the file, and if an element contains children,
// output information about the child key and value
for($chapte-->rewind(); $chapter->valid(); $chapter->next() ) {
foreach($chapter->getChildren() as $name => $data) {
echo "{$name}: {$data}
";
}
}
?>
Executing this snippet produces the following output:
code: date()
emphasis: must
glossterm: input parameter
Beyond Iterators: Other SPL Features
Iterators are only one part of what the SPL has to offer. Be sure to check out these other great features:
- Advanced Data Structures: The SPL offers several advanced data structures, including heaps, stacks, queues, doubly linked lists, and a fixed array.
- Exceptions: The SPL offers 13 context-specific exceptions useful for further clarifying the intent of your code. Examples of custom exceptions include
LengthException
,LogicException
,OverflowException
andRuntimeException
. - File Handling: You can use the SPL’s file handling classes to uncover a great deal of information about system files, the path, modification timestamp, creation timestamp, owner, and much more.
Conclusion
Are you using the SPL in interesting ways? Tell us how in the comments!
About the Author
Jason Gilmore is founder of the publishing, training, and consulting firm WJGilmore.com. He is the author of several popular books, including “Easy PHP Websites with the Zend Framework”, “Easy PayPal with PHP”, and “Beginning PHP and MySQL, Fourth Edition”. Follow him on Twitter at @wjgilmore.