PHP SimpleXML

Beginner
10 min read
Updated: Nov 2026
3 examples
Read, query & build XML

Definition and Usage

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.

There are three ways to load XML. Use simplexml_load_string() for XML in a variable, simplexml_load_file() for a file or URL, and new SimpleXMLElement() when you prefer an object and an exception on bad XML. If you already have a DOMNode, simplexml_import_dom() turns it into a SimpleXML element that shares the same data.

Once loaded, you can read data with children() and attributes(), search with xpath(), change the tree with addChild() and addAttribute(), and write it back out with asXML().

This page explains the ideas. The SimpleXML Functions index lists all 24 function guides.

Pick the right tool.

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).

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

Core Ideas

What to remember when you work with SimpleXML:

IdeaFunctionRemember
Load a stringsimplexml_load_string()Returns the root element, or false on bad XML; use libxml_use_internal_errors(true) to collect the errors
Load a filesimplexml_load_file()Same result as the string version; the path can be a local file or a URL if your PHP settings allow it
ConstructorSimpleXMLElement::__construct()Throws an Exception on bad XML; pass true as the third argument to load from a file or URL
Property accessgetName() / children()$xml->book is the first book; use $xml->book[1] for the next, or foreach for all of them
Attributesattributes()Read one with $el['name'], or loop over all of them with $el->attributes()
Countingcount()count($xml->book) counts matching siblings; count($xml) counts the children of one element
Cast to textSimpleXMLElement::__toString()Gives the text of the element only, without the text of its children; this is what (string) and echo use
Searchxpath()Returns an array of matching elements; use registerXPathNamespace() before you query a document that has namespaces
BuildaddChild() / addAttribute()Both change the tree in memory; addChild() returns the new element so you can keep adding to it
ExportasXML() / saveXML()Without an argument they return a string; with a file name they write the file and return true or false

Namespaces and iteration

For documents with prefixes such as dc:title, list the prefixes with getNamespaces() or getDocNamespaces(), then read the elements with $xml->children($uri). SimpleXML also works as an iterator, so the methods rewind(), valid(), current(), key() and next(), together with hasChildren() and getChildren(), are what foreach and RecursiveIteratorIterator call for you.

SimpleXML vs XML Parser vs DOM

PHP has three common ways to read XML. They read the same documents but suit different jobs:

TopicSimpleXMLXML Parser (Expat)DOM
ModelTree of objects, read like propertiesEvent-driven stream, no treeFull tree of node objects
MemoryWhole document in memorySmall and steady, even for huge filesWhole document in memory, usually more than SimpleXML
Code lengthShortest for readingLongest: you write the handlers and keep stateMedium to long
EditingAdd children and attributes, change textRead onlyFull control: insert, move, remove, comments, CDATA
Searchxpath()None, you test each tag yourselfDOMXPath
Best forConfig files, feeds, API responsesVery large files, early stopPrecise 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.

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.

PHP
<?php
$xml = '<library>'
     . '<book id="1" lang="en"><title>Learn PHP</title><price>29.50</price></book>'
     . '<book id="2" lang="fr"><title>XML Basics</title><price>19.00</price></book>'
     . '</library>';

$library = simplexml_load_string($xml);

echo 'First: ', $library->book[0]->title, PHP_EOL;
echo 'Count: ', count($library->book), PHP_EOL;

$total = 0;
foreach ($library->book as $book) {
    echo $book['id'], ': ', $book->title, ' (', $book['lang'], ')', PHP_EOL;
    $total += (float) $book->price;
}

echo 'Total price: ', $total, PHP_EOL;
?>

How It Works

  1. 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.
  2. $library->book[0]->title picks the first book and then its title. echo turns the element into its text, Learn PHP.
  3. count($library->book) counts the sibling book elements, so it prints 2. The same foreach loop visits each one in document order.
  4. Inside the loop, $book['id'] and $book['lang'] read the attributes with array syntax.
  5. (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.

PHP
<?php
$xml = '<cart><item sku="A1">Pen</item><item sku="B2">Book</item></cart>';

$cart = simplexml_load_string($xml);

$item = $cart->addChild('item', 'Lamp');
$item->addAttribute('sku', 'C3');

echo 'Items: ', count($cart->item), PHP_EOL;

$found = $cart->xpath('//item[@sku="C3"]');
echo 'Found: ', $found[0], PHP_EOL;
echo 'Item XML: ', $item->asXML(), PHP_EOL;

$skus = [];
foreach ($cart->xpath('//item/@sku') as $sku) {
    $skus[] = (string) $sku;
}
echo 'SKUs: ', implode(',', $skus), PHP_EOL;
?>
xpath() Tutorial

How It Works

  1. 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.
  2. addAttribute('sku', 'C3') sets the attribute on that new item. The tree now has three item elements, so count() prints 3.
  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.
  4. 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.
  5. 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.

PHP
<?php
$xml = '<product id="42" active="true">'
     . '<name>Desk</name><stock>7</stock>'
     . '<tags><tag>wood</tag><tag>office</tag></tags>'
     . '</product>';

$p = simplexml_load_string($xml);

echo 'Root: ', $p->getName(), PHP_EOL;
echo 'Type: ', get_class($p->name), PHP_EOL;
echo 'Cast: ', gettype((string) $p->name), PHP_EOL;
echo 'Stock + 1: ', (int) $p->stock + 1, PHP_EOL;

$attrs = [];
foreach ($p->attributes() as $name => $value) {
    $attrs[] = $name . '=' . $value;
}
echo 'Attributes: ', implode(', ', $attrs), PHP_EOL;

$names = [];
foreach ($p->children() as $child) {
    $names[] = $child->getName();
}
echo 'Children: ', implode(', ', $names), PHP_EOL;

echo 'Second tag: ', $p->tags->tag[1], PHP_EOL;
echo 'Has missing: ', isset($p->missing) ? 'yes' : 'no', PHP_EOL;
?>

How It Works

  1. getName() returns the tag name of an element. On the root it is product.
  2. $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.
  3. 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 ..
  4. children() returns the direct child elements only: name, stock and tags. The two tag elements are grandchildren, so they are not in the list.
  5. $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.

Next: PHP SimpleXML Functions Index

After you know how to load, read, query, and build XML, open the functions index for all 24 guides.

Start withWhy
simplexml_load_string()Load XML from a string and handle bad input
simplexml_load_file()Load XML from a file or a URL
attributes()Read the attributes of an element
children()Loop over child elements, with or without a namespace
xpath()Find elements and attributes with a query
addChild()Append a new element to the tree
asXML()Export the tree as a string or write it to a file

Full list: PHP SimpleXML Functions index (/php/simple-xml/function).

Frequently Asked Questions

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.

Browse every SimpleXML function

Open the functions index for categorized guides with examples and FAQs.

SimpleXML Functions Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful