PHPBuilder - Using SPL Iterators in PHP to Interact with Different Data Types Page 2



RSS Twitter
Articles Php Functions

Using SPL Iterators in PHP to Interact with Different Data Types - Page 2

by: W. Jason Gilmore
|
March 16, 2011

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 and RuntimeException.
  • 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.

« Previous Page
1
|
2

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
W. Jason Gilmore

Comment:



Comment:

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