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.
There are two ways to read XML
under SimpleXML. If your XML document is stored as a string in a PHP
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 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 ...