5.4 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.

5.4.1 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');

5.4.2 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.

Figure 5-2. A SimpleXML representation of an XML address book

To access a single value, reference it directly using object method notation. Here's the same snippet from the DOM section:


If you have this in a SimpleXML object, $firstname, here's all you need to do to access Rasmus:


SimpleXML assumes that when you have a node that contains only text, you're interested in the text. Therefore, print $firstname does what you expect it to: it prints Rasmus.

Iteration methods, like foreach, are the best choice for cycling through multiple elements. Code for this is shown in later examples.

Unlike DOM, attributes are not stored as separate nodes. Instead, attributes are stored as array elements. For example, this prints out the id attribute for the first person element:

$ab = simplexml_load_file('address-book.xml');

// the id attribute of the first person

print $ab->person['id'] . "\n";

which gives you:


5.4.3 Turning SimpleXML Objects into XML Documents

The asXML( ) method converts a SimpleXML object back into an XML string:

// display the XML

print $ab->asXML( );

The asXML( ) method can save the XML to a file by passing the location of the output file as an argument:

// save the XML


This method also works on subnodes. For instance:

$ab = simplexml_load_file('address-book.xml');

print $ab->person->firstname->asXML( );