O'Reilly logo

Upgrading to PHP 5 by Adam Trachtenberg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

SimpleXML

SimpleXML has been described as “the mostest bestest thing ever.” While it’s hard to live up to such grand praise, SimpleXML does do a remarkable job of making it—dare I say—simple to interact with XML. When you want to read a configuration file written in XML, parse an RSS feed, or process the result of a REST request, SimpleXML excels at these tasks. It doesn’t work well for more complex XML-related jobs, such as reading a document where you don’t know the format ahead of time or when you need to access processing instructions or comments.

Turning XML Documents into SimpleXML Objects

There are two ways to read XML under SimpleXML. If your XML document is stored as a string in a PHP variable, use simplexml_load_string( ). If it’s in a file, call simplexml_load_file( ) instead. For instance:

// Variable
$xml = simplexml_load_string('<xml>I am XML</xml>');

// Local file
$people = simplexml_load_file('address-book.xml');

SimpleXML Elements

SimpleXML turns elements into object properties. The text between the tags is assigned to the property. If more than one element with the same name lives in the same place (such as multiple <people>s), then they’re placed inside a list.

Element attributes become array elements, where the array key is the attribute name and the key’s value is the attribute’s value.

Figure 5-2 shows SimpleXML’s view of the start of the address book.

A SimpleXML representation of an XML address book

Figure 5-2. A ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required