PHP SimpleXML – Get Node/Attribute Values

PHP SimpleXML provides methods for accessing specific nodes and attributes in an XML document using object properties and methods. Here are some examples of how to use SimpleXML to get node and attribute values:

  1. Get node values
$xmlString = '<books><book><title>PHP and XML</title></book></books>';
$xml = simplexml_load_string($xmlString);
echo $xml->book[0]->title; // Output: PHP and XML

In this example, we use the simplexml_load_string() function to parse an XML string into an object. We can then access the book titles using object properties and methods.

  1. Get attribute values
$xmlString = '<book category="programming"><title>PHP and XML</title></book>';
$xml = simplexml_load_string($xmlString);
echo $xml['category']; // Output: programming

In this example, we have an XML element that contains an attribute called “category”. We use the object’s properties to access the attribute value.

  1. Get multiple node values
$xmlString = '<books><book><title>PHP and XML</title></book><book><title>JavaScript and JSON</title></book></books>';
$xml = simplexml_load_string($xmlString);
foreach ($xml->book as $book) {
    echo $book->title . '<br>';
}

In this example, we use the foreach loop to iterate over all the book elements in the XML document, and access the title of each book using object properties and methods.

  1. Get node values with attributes
$xmlString = '<book category="programming"><title>PHP and XML</title><author>Jane Doe</author></book>';
$xml = simplexml_load_string($xmlString);
echo $xml->title . ' by ' . $xml->author . ' (' . $xml['category'] . ')'; // Output: PHP and XML by Jane Doe (programming)

In this example, we use object properties and methods to access the title and author of a book, as well as the category attribute of the book element.

Overall, SimpleXML provides a simple and easy-to-use interface for accessing specific nodes and attributes in an XML document using object properties and methods.