← Back to PHP Course | Chapter 14: Advanced PHP | Lesson 22 of 24

PHP SimpleXML Get

Beyond basic property access, SimpleXML offers a family of dedicated methods -- attributes(), children(), xpath() -- for more precise and powerful ways to pull specific values out of an XML document, especially useful for XML with a more complex or variable structure than a straightforward property chain can handle.

Getting All Attributes with attributes()

An XML element's attributes() method returns all of its attributes as an iterable collection, useful when an element has several attributes you want to process together, rather than accessing each one individually by name.

Note: Loop over attributes() with foreach when you need to process every attribute generically, rather than knowing each attribute's name in advance.

Warning: attributes() returns only the attributes on that specific element, not on any of its children -- each nested element needs its own separate attributes() call.

Example: Getting All Attributes with attributes()

php
<?php
$xml = simplexml_load_string('<book id="1" lang="en">PHP Basics</book>');
foreach ($xml->attributes() as $name => $value) {
    echo "$name: $value\n";
}
?>

Getting Child Elements with children()

The children() method returns an element's direct child elements as an iterable collection, similar to accessing a known property name directly, but useful when a document's exact child tag names are not known ahead of time, or when working generically across varying XML structures.

Note: Use children() for generic XML processing where tag names might vary; use direct property access ($xml->tagName) when you already know the exact structure.

Warning: children() only returns the immediate children of the element it is called on -- grandchildren and deeper descendants require calling children() again on each level, or using xpath() instead.

Example: Getting Child Elements with children()

php
<?php
$xml = simplexml_load_string("<book><title>PHP Basics</title><author>Alice</author></book>");
foreach ($xml->children() as $child) {
    echo $child->getName() . ": " . $child . "\n";
}
?>

Querying with XPath

xpath($query) runs an XPath query -- a purpose-built pattern language for navigating XML -- against the document, returning an array of every matching element. XPath is especially powerful for reaching deeply nested or conditionally-matched elements without writing out a long property chain.

Note: Use a simple path expression like '//title' to find every <title> element anywhere in the document, regardless of nesting depth.

Warning: xpath() always returns an array, even for a query matching exactly one element -- remember to access [0] to get that single matched SimpleXMLElement out of the array.

Example: Querying with XPath

php
<?php
$xml = simplexml_load_string("<catalog><book><title>PHP Basics</title></book></catalog>");
$results = $xml->xpath("//title");
echo $results[0];
?>

Getting Text Content vs Elements

Calling (string) on a SimpleXMLElement extracts just its plain text content, discarding its object-like structure -- useful when you specifically need the raw text value rather than a SimpleXMLElement object, such as before using the value in a string comparison or database query.

Note: Explicitly cast to (string) before comparing a SimpleXML value with ==, since comparing a SimpleXMLElement object directly to a plain string can behave unexpectedly.

Warning: Forgetting to cast to string before passing a SimpleXML value into a function expecting a plain string (like a database bind_param call) can cause type errors or unexpected behavior.

Example: Getting Text Content vs Elements

php
<?php
$xml = simplexml_load_string("<book>PHP Basics</book>");
$text = (string) $xml;
var_dump($text);
?>

Handling Namespaced XML

Some XML documents use namespaces -- a prefix like atom: on tag names to avoid naming conflicts between different XML vocabularies mixed in one document -- and SimpleXML requires the children() and attributes() methods to be given the namespace URI explicitly to access namespaced elements correctly.

Note: Check an XML document's root element for xmlns declarations to identify any namespaces you will need to pass explicitly when accessing their elements.

Warning: Attempting to access a namespaced element with plain property syntax (without specifying its namespace) typically returns nothing, since SimpleXML treats namespaced and non-namespaced elements as entirely distinct.

Example: Handling Namespaced XML

php
<?php
$xml = simplexml_load_string('<feed xmlns:atom="http://www.w3.org/2005/Atom"><atom:title>My Feed</atom:title></feed>');
$children = $xml->children('atom', true);
echo $children->title;
?>
Common Mistakes
  1. Trying to access an XML attribute with the -> operator (like $xml->id) instead of array-bracket syntax ($xml[id]), which is how SimpleXML distinguishes attributes from child elements.
  2. Writing a fragile, deeply chained property-access path for data that would be more robustly and flexibly retrieved with an xpath() query.
  3. Forgetting that xpath() always returns an array of matches, even when you expect exactly one result, requiring an extra [0] to get the single matched element.
Chapter Summary
  • attributes() returns an element's XML attributes as an iterable collection.
  • children() returns an element's direct child elements, useful when working with data whose exact tag names are not known in advance.
  • xpath($query) runs an XPath query against the document, a powerful pattern-matching language for locating specific nodes anywhere in an XML tree.
Browser Support

SimpleXML's attributes(), children(), and xpath() methods have all been available since SimpleXML was introduced in PHP 5.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.