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.
Figure 5-2. A SimpleXML representation of an XML address book
To access a single value, ...
Get Upgrading to PHP 5 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.