PHP › XML Handling in PHP
How does SimpleXML let you access nested elements and attributes within an XML document using a natural, object like syntax?
BeginnerAnswer
SimpleXML converts an entire XML document into a tree of PHP objects, letting you navigate nested elements simply by chaining together property access using the arrow operator, similar to accessing regular object properties, and an XML attribute, meaning a piece of data attached directly to an opening tag rather than nested as its own separate element, can be accessed using array style square bracket syntax on that same element object, making common XML reading tasks feel quite natural and intuitive for a PHP developer already familiar with regular objects and arrays.
$xml = simplexml_load_string('<product id="42"><name>Widget</name></product>');
echo $xml['id']; // 42
echo $xml->name; // WidgetReal-world example An application reading product data from an XML feed accesses each product's id attribute using array style syntax and its nested name element using regular object property syntax, both through the same simple, intuitive SimpleXML interface.