PHP SimpleXML Get
In this page:
foreach ($xml->attributes() as $name => $value) { }
foreach ($xml->children() as $child) { }
$results = $xml->xpath("//element_name");
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.
Example: Getting All Attributes with attributes()
<?php
// Declare `$xml`, set to `simplexml_load_string('<book id="1" lang="en">PHP Basics</book>')`
$xml = simplexml_load_string('<book id="1" lang="en">PHP Basics</book>');
// Loop over `$xml->attributes()`, binding each item to `$name => $value`
foreach ($xml->attributes() as $name => $value) {
// Print "$name: $value\n" to the output
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.
Example: Getting Child Elements with children()
<?php
// Declare `$xml`, set to `simplexml_load_string("<book><title>PHP Basics</title><author>Alice</author></book>")`
$xml = simplexml_load_string("<book><title>PHP Basics</title><author>Alice</author></book>");
// Loop over `$xml->children()`, binding each item to `$child`
foreach ($xml->children() as $child) {
// Print `$child->getName() . ": " . $child . "\n"` to the output
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.
Example: Querying with XPath
<?php
// Declare `$xml`, set to `simplexml_load_string("<catalog><book><title>PHP Basics</title></book></catalog>")`
$xml = simplexml_load_string("<catalog><book><title>PHP Basics</title></book></catalog>");
// Declare `$results`, set to `$xml->xpath("//title")`
$results = $xml->xpath("//title");
// Print `$results[0]` to the output
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.
Example: Getting Text Content vs Elements
<?php
// Declare `$xml`, set to `simplexml_load_string("<book>PHP Basics</book>")`
$xml = simplexml_load_string("<book>PHP Basics</book>");
// Declare `$text`, set to `(string) $xml`
$text = (string) $xml;
// Print a detailed dump (with types) of `$text`
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.
Example: Handling Namespaced XML
<?php
// Declare `$xml`, set to `simplexml_load_string('<feed xmlns:atom="http://www.w3.org/2005/Atom"><atom:title>My Feed</atom:title></feed>')`
$xml = simplexml_load_string('<feed xmlns:atom="http://www.w3.org/2005/Atom"><atom:title>My Feed</atom:title></feed>');
// Declare `$children`, set to `$xml->children('atom', true)`
$children = $xml->children('atom', true);
// Print `$children->title` to the output
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