Parsing XML using PHP5by: Burhan KhalidParsing XML using PHP5 This tutorial is a follow up to my earlier tutorial, Parsing XML using PHP4 and highlights the improvements in XML handling with PHP5. The release of PHP5 updated PHP with much needed OOP features with the release of a new object model. In addition, support for MySQL 4.1.x (with the improved mysqli extension) and a whole host of changes where introduced with PHP5. The most significant change with regards to XML is the introduction of the simplexml extension, which provides a complete set of tools for parsing XML documents. I'll concentrate on the XML-bits (for now). Simplexml is enabled by default with PHP5, so anyone running PHP5 should be ready to go. Simplexml provides a very easy framework for parsing XML documents. For example, there are functions to load XML documents from a file, or from a string. In addition, the Note: This example will work if you have your url wrappers enabled. PHP:
The simplexml_* functions return an object of class SimpleXMLElement. You can then use this object to perform operations on the XML file. The object returned with simplxml_load_file represents the entire structure of the XML file as properties of the object. Each tag is turned into a SimpleXMLElement object, and so on. Here is what the feed that you get from bash.org looks like : XML:
The resulting SimpleXMLElement object that you get looks something like : CODE:
You'll note that the description itself is an object, but its contents are the actual quote. PHP5 provides object iteration which allows you to query the properties of an object, much like you would those of an array. So, when we query the description object : PHP:
We get the following output: CODE:
Now it becomes clear. The description object holds the description (the quote) that we are after. Now its easy to see why my two-liner at the very beginning outputs the correct results. This is only scratching the surface of the new simplexml extension with PHP5. You can, for example, write your own class that extends SimpleXMLElement, and then have all the simplexml_* functions return an object of your class, not the default SimpleXMLElement class -- allowing for increased flexibility and ease when dealing with XML documents. © 2008 NetVisits, Inc. All rights reserved. |