PHP SimpleXML Get
In this page:
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
$xml = simplexml_load_string('<book id="1" lang="en">PHP Basics</book>');
foreach ($xml->attributes() as $name => $value) {
echo "$name: $value\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
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
$xml = simplexml_load_string("<book><title>PHP Basics</title><author>Alice</author></book>");
foreach ($xml->children() as $child) {
echo $child->getName() . ": " . $child . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
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
$xml = simplexml_load_string("<catalog><book><title>PHP Basics</title></book></catalog>");
$results = $xml->xpath("//title");
echo $results[0];
?>
Login to try C/C++/Java/PHP code in the editor
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
$xml = simplexml_load_string("<book>PHP Basics</book>");
$text = (string) $xml;
var_dump($text);
?>
Login to try C/C++/Java/PHP code in the editor
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
$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;
?>
Login to try C/C++/Java/PHP code in the editor
- 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.
- Writing a fragile, deeply chained property-access path for data that would be more robustly and flexibly retrieved with an xpath() query.
- 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.
- 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.
SimpleXML's attributes(), children(), and xpath() methods have all been available since SimpleXML was introduced in PHP 5.
Chapter Quiz — Complete all 24 topics to unlock
0/24 topics done
Complete these topics first:
- PHP Date & Time
- PHP Math Functions
- PHP JSON Handling
- PHP XML Handling
- PHP cURL Introduction
- PHP REST API Basics
- PHP Composer & Packages
- PHP Autoloading
- PHP Design Patterns
- PHP MVC Architecture
- PHP Security Best Practices
- PHP Performance Optimization
- PHP 8 New Features
- PHP Type Declarations
- PHP Match Expression Advanced
- PHP Fibers
- PHP Attributes
- PHP Magic Constants
- PHP Include & Require
- PHP Iterables
- PHP SimpleXML Parser
- PHP SimpleXML Get
- PHP XML Expat Parser
- PHP DOM Parser