[ Team LiB ] Previous Section Next Section

Introducing SimpleXML

Do the examples in this chapter seem like a lot of hard work to you? XML is powerful, and DOM in particular contains complexities that must be followed to build compliant parsers. Sometimes, however, you might want to trade off power for ease of use. SimpleXML is just that, an easy and quick way of accessing and amending XML data.

At the time of writing, just two functions are available for SimpleXML: simplexml_load_file() and simplexml_load_string(). The first expects a file path, and the second an XML string. Both functions parse XML and return a simplexml_element object that contains properties named according to the elements found. So, in our banana example, it would contain a property called $newsitem. If more than one element with that name exists at the same level, $newsitem contains an array; otherwise, it holds a value. If the element in question contains other elements, the property contains an additional simplexml_element object (or array of objects). Finally, if the element in question contains text, the property contains a string (or array of strings).

This sounds much more complicated than it is in practice. Let's revisit the banana news example (see Listing 22.9).

Listing 22.9 Parsing an XML Document with SimpleXML
1: <?php
2: $simple_element = simplexml_load_file("listing22.1.xml");
4: foreach ( $simple_element->newsitem as $item ) {
5:   print "<b>{$item->headline}</b><br />\n";
6:   print "<i>{$item->byline}</i><br />\n\n";
7: }
8: ?>

Listing 22.9 is certainly simple! We acquire a simplexml_element object by calling the simplexml_load_file() function, passing it the path to an XML file. We then loop through the $newsitem property that we know had been made available, printing text elements to the browser. In a real-world example, we would have tested the $simple_element object before working with it.

SimpleXML is very much under development. As this book goes to press, it is not yet stable and clearly does not contain all the functions it will. Some examples refer to a simplexml_save_document_file() function that should let you save amended data back to an XML file. This has been removed from early distributions of PHP 5, although it is likely that it, or something like it, will reappear. You should look out for SimpleXML documentation on the PHP manual at http://www.php.net/manual/en.

    [ Team LiB ] Previous Section Next Section