Skip to content

PHP SimpleXML - Get

PHP SimpleXML - Retrieving Node and Attribute Values

Section titled “PHP SimpleXML - Retrieving Node and Attribute Values”

SimpleXML is a built-in PHP extension that provides an intuitive way to parse and manipulate XML data. It represents an XML document as an object, making data access straightforward.

While SimpleXML is convenient for basic XML tasks, for complex manipulations or very large files, consider using the DOMDocument or XMLReader extensions.

To read an XML file, use the simplexml_load_file() function. It returns a SimpleXMLElement object on success, or false on failure. Always check the return value before proceeding.

Consider this simple XML file, note.xml:

<?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>

Here’s how to get the node values from note.xml:

<?php
declare(strict_types=1);
$xmlFilePath = "note.xml";
if (!file_exists($xmlFilePath)) {
echo "Error: File not found ({$xmlFilePath})";
exit;
}
// Load the XML file
$xml = simplexml_load_file($xmlFilePath);
// Check if loading was successful
if ($xml === false) {
echo "Error: Cannot create SimpleXMLElement object.";
// You might want to log specific XML errors here using libxml_get_errors()
// libxml_use_internal_errors(true);
// $xml = simplexml_load_file(...);
// if ($xml === false) { foreach(libxml_get_errors() as $error) { echo $error->message; } }
exit;
}
// Access node values as object properties
// Casting to string is often implicit but good for clarity
echo (string)$xml->to . "<br>";
echo (string)$xml->from . "<br>";
echo (string)$xml->heading . "<br>";
echo (string)$xml->body;
?>

The expected output of the code above is:

Tove<br>Jani<br>Reminder<br>Don't forget me this weekend!

Let’s use a more complex XML file, books.xml, for further examples:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J. K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en-us">XQuery Kick Start</title>
<author>James McGovern</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="WEB">
<title lang="en-us">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

PHP SimpleXML - Accessing Specific Elements

Section titled “PHP SimpleXML - Accessing Specific Elements”

When multiple elements share the same name (like <book>), SimpleXML treats them as an iterable collection accessible via array-like index notation.

This example retrieves the <title> of the first (index 0) and second (index 1) <book> elements:

<?php
declare(strict_types=1);
$xmlFilePath = "books.xml";
if (!file_exists($xmlFilePath)) {
die("Error: File not found ({$xmlFilePath})");
}
$xml = simplexml_load_file($xmlFilePath);
if ($xml === false) {
die("Error: Cannot create object");
}
// Check if book elements exist before accessing
if (isset($xml->book[0])) {
echo (string)$xml->book[0]->title . "<br>";
}
if (isset($xml->book[1])) {
echo (string)$xml->book[1]->title;
}
?>

The expected output is:

Everyday Italian<br>Harry Potter

You can easily iterate over elements with the same name using a foreach loop. The children() method can be used, but often direct iteration on the parent property works.

This example loops through all <book> elements and prints their details:

<?php
declare(strict_types=1);
$xmlFilePath = "books.xml";
if (!file_exists($xmlFilePath)) {
die("Error: File not found ({$xmlFilePath})");
}
$xml = simplexml_load_file($xmlFilePath);
if ($xml === false) {
die("Error: Cannot create object");
}
// Iterate directly over the <book> elements
foreach ($xml->book as $book) {
echo htmlspecialchars((string)$book->title, ENT_QUOTES, 'UTF-8') . ", ";
echo htmlspecialchars((string)$book->author, ENT_QUOTES, 'UTF-8') . ", ";
echo htmlspecialchars((string)$book->year, ENT_QUOTES, 'UTF-8') . ", ";
echo htmlspecialchars((string)$book->price, ENT_QUOTES, 'UTF-8') . "<br>";
}
?>

Note: We use htmlspecialchars() here to safely output the text content in an HTML context, preventing potential Cross-Site Scripting (XSS) if the XML data came from an untrusted source.

The expected output is:

Everyday Italian, Giada De Laurentiis, 2005, 30.00<br>Harry Potter, J. K. Rowling, 2005, 29.99<br>XQuery Kick Start, James McGovern, 2003, 49.99<br>Learning XML, Erik T. Ray, 2003, 39.95<br>

Attributes are accessed using array-like notation on the element object.

This example gets the category attribute of the first <book> and the lang attribute of the <title> element within the second <book>:

<?php
declare(strict_types=1);
$xmlFilePath = "books.xml";
if (!file_exists($xmlFilePath)) {
die("Error: File not found ({$xmlFilePath})");
}
$xml = simplexml_load_file($xmlFilePath);
if ($xml === false) {
die("Error: Cannot create object");
}
// Access attributes using array notation
if (isset($xml->book[0]['category'])) {
echo (string)$xml->book[0]['category'] . "<br>";
}
if (isset($xml->book[1]->title['lang'])) {
echo (string)$xml->book[1]->title['lang'];
}
?>

The expected output is:

COOKING<br>en

PHP SimpleXML - Looping Through Attributes

Section titled “PHP SimpleXML - Looping Through Attributes”

You can combine looping through elements and accessing their attributes.

This example retrieves the lang attribute from the <title> element of each <book>:

<?php
declare(strict_types=1);
$xmlFilePath = "books.xml";
if (!file_exists($xmlFilePath)) {
die("Error: File not found ({$xmlFilePath})");
}
$xml = simplexml_load_file($xmlFilePath);
if ($xml === false) {
die("Error: Cannot create object");
}
foreach ($xml->book as $book) {
// Check if the lang attribute exists before accessing
if (isset($book->title['lang'])) {
echo htmlspecialchars((string)$book->title['lang'], ENT_QUOTES, 'UTF-8');
} else {
echo "(no lang attribute)"; // Handle cases where attribute might be missing
}
echo "<br>";
}
?>

The expected output is:

en<br>en<br>en-us<br>en-us<br>

For comprehensive details on SimpleXML functions and their usage, consult the official PHP Manual: https://www.php.net/manual/en/book.simplexml.php