PHP SimpleXML - Get

PHP SimpleXML - Get Node Values

Once you have parsed an XML document into a SimpleXMLElement object, retrieving the data inside it is as easy as accessing standard PHP object properties.


Extracting Node Values

You can get the value of specific XML nodes by using standard object notation (->). Let's extract the "to" and "heading" from a note.

Get Node Value Example

<?php
$myXMLData = "<?xml version='1.0' encoding='UTF-8'?>
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>";

$xml = simplexml_load_string($myXMLData);

// Accessing specific nodes echo "To: " . $xml->to . "\n"; echo "Heading: " . $xml->heading . "\n"; ?>


Getting Attribute Values

XML nodes can contain attributes. For example, <book category="fiction">. To read an attribute from a SimpleXML object, you access the object as if it were an associative array!

Get Attribute Example

<?php
$xmlString = "
<library>
  <book category='fiction'>Harry Potter</book>
</library>";

$xml = simplexml_load_string($xmlString);

// Accessing the category attribute using array notation echo "Category: " . $xml->book['category'] . "\n"; echo "Title: " . $xml->book; ?>


Exercise

?

How do you extract an XML attribute (e.g., category) from a node object named $book?