SimpleXML lets you work with XML the way you work with a PHP object. You load a document once, and the result is a SimpleXMLElement for the root element. From there, a child element is a property ($xml->title), an attribute is an array key ($xml->book['id']), and repeated elements can be looped over with foreach.
SimpleXML is the fastest way to read a config file, a feed, or an API response. If the file is huge, use the XML Parser instead; SimpleXML keeps the whole tree in memory.
Every node is an object.
$xml->title is a SimpleXMLElement, not a string. echo converts it to text for you, but when you compare, store, or pass a value on, cast it first with (string), (int), or (float).
Syntax
PHP Syntax
The usual pattern: load the XML, check the result, read values, then change or export if you need to:
PHP
// Load: SimpleXMLElement on success, false on bad XML
$xml = simplexml_load_string($string); // from a string
$xml = simplexml_load_file('data.xml'); // from a file or URL
$xml = new SimpleXMLElement($string); // throws Exception on bad XML
// Read
echo $xml->book[0]->title; // element as a property
echo $xml->book[0]['id']; // attribute as an array key
echo $xml->{'first-name'}; // names with a dash need braces
foreach ($xml->book as $book) { } // repeated elements
foreach ($xml->children() as $child) { } // every child element
foreach ($xml->attributes() as $k => $v) { } // every attribute
// Query: array of SimpleXMLElement, or false
$nodes = $xml->xpath('//book[@lang="en"]');
// Change and export
$item = $xml->addChild('book'); // SimpleXMLElement
$item->addAttribute('id', '3');
echo $xml->asXML(); // string, with the XML declaration
$xml->asXML('out.xml'); // bool, writes to a file
// Cast to a plain value
$title = (string) $xml->book[0]->title; // string
$price = (float) $xml->book[0]->price; // float
Whole document in memory, usually more than SimpleXML
Code length
Shortest for reading
Longest: you write the handlers and keep state
Medium to long
Editing
Add children and attributes, change text
Read only
Full control: insert, move, remove, comments, CDATA
Search
xpath()
None, you test each tag yourself
DOMXPath
Best for
Config files, feeds, API responses
Very large files, early stop
Precise edits and schema validation
You do not have to choose once. simplexml_import_dom() wraps a DOM node as SimpleXML, and dom_import_simplexml() goes the other way, so you can read with SimpleXML and drop to DOM only for the one edit it cannot do. To collect errors from broken XML, see PHP libxml.
Code
PHP Examples
Three short scripts that show how SimpleXML works. Each one loads a small XML string written in the script itself with simplexml_load_string(), so the output is the same every time you run it.
Example 1 — Read elements and attributes
Load a small library, read the first book, loop over every book, and add up the prices.
First: Learn PHP
Count: 2
1: Learn PHP (en)
2: XML Basics (fr)
Total price: 48.5
How It Works
simplexml_load_string() parses the string and returns a SimpleXMLElement for the root, <library>. The root itself is not part of the path: you write $library->book, not $library->library->book.
$library->book[0]->title picks the first book and then its title. echo turns the element into its text, Learn PHP.
count($library->book) counts the sibling book elements, so it prints 2. The same foreach loop visits each one in document order.
Inside the loop, $book['id'] and $book['lang'] read the attributes with array syntax.
(float) $book->price casts the text to a number before it is added. 29.50 + 19.00 is 48.5, and PHP drops the trailing zero when it prints a float.
Example 2 — xpath(), addChild(), addAttribute() and asXML()
Add a new item to a cart, find it with an XPath query, and print it back as XML.
addChild('item', 'Lamp') appends <item>Lamp</item> to the cart and returns the new element, which is why you can call addAttribute() on it straight away.
addAttribute('sku', 'C3') sets the attribute on that new item. The tree now has three item elements, so count() prints 3.
xpath('//item[@sku="C3"]') searches the whole document and always returns an array of matches. Here there is one, so $found[0] is the Lamp element.
asXML() on a child returns just that element as a string. Called on the root, it also adds the <?xml version="1.0"?> line at the top.
An XPath that ends in an attribute, //item/@sku, returns the attribute nodes. Cast each one with (string) to get plain text.
Example 3 — Casting, attributes() and children()
Inspect a product: confirm that nodes are objects, cast them to real values, and list the attributes and child names.
Root: product
Type: SimpleXMLElement
Cast: string
Stock + 1: 8
Attributes: id=42, active=true
Children: name, stock, tags
Second tag: office
Has missing: no
How It Works
getName() returns the tag name of an element. On the root it is product.
$p->name is still a SimpleXMLElement, which get_class() proves. Casting it with (string) gives a real PHP string, and (int) $p->stock gives a real integer, so + 1 works as 8.
attributes() returns the attributes of the element. In a foreach, the key is the attribute name and the value is a node that joins into a string with ..
children() returns the direct child elements only: name, stock and tags. The two tag elements are grandchildren, so they are not in the list.
$p->tags->tag[1] walks down and picks the second tag, which is office. isset() is the safe way to test for a child: a missing element does not exist, so the answer is no.
Continue
Next: PHP SimpleXML Functions Index
After you know how to load, read, query, and build XML, open the functions index for all 24 guides.
SimpleXML is a PHP extension that turns an XML document into an object you can walk with normal PHP syntax. Elements become properties, attributes become array keys, and repeated elements behave like arrays. It builds the whole tree in memory, so it is quick to write and easy to read, and best suited to small and medium documents.
Use simplexml_load_string($xml) when the XML is already in a variable, or simplexml_load_file($path) when it is in a file or a URL. Both return a SimpleXMLElement for the root element, or false if the XML is not well formed. You can also write new SimpleXMLElement($xml), which throws an exception on bad XML instead of returning false.
Use array syntax on the element: $book['id']. The result is a SimpleXMLElement, not a plain string, so cast it with (string) or (int) when you need a real value. To loop over all attributes of an element, use foreach ($book->attributes() as $name => $value).
echo converts a SimpleXMLElement to its text for you, but a node is still an object. Comparisons, array keys, and strict checks should use a cast: (string) $node, (int) $node, or (float) $node. A missing element still gives you an empty SimpleXMLElement object, so use isset() to test whether a child exists.
Use SimpleXML to read and make small edits to documents of ordinary size. Use the XML Parser (Expat) for very large files you want to read as a stream with a small, steady memory use. Use DOM when you need full control, such as inserting nodes at an exact position, working with comments and processing instructions, or validating against a schema.
simplexml_load_string() and simplexml_load_file() return false and raise warnings when the XML is broken. Call libxml_use_internal_errors(true) first, then read the problems with libxml_get_errors() and clear them with libxml_clear_errors(). That keeps warnings out of your page and lets you show a clear message.