PHP SimpleXML - simplexml_load_file and simplexml_load_string
PHP's SimpleXML extension provides an easy way to parse and manipulate XML data. In this article, we will dive deep into the SimpleXML extension and explore its
How to Get and Read XML with PHP SimpleXML
PHP's SimpleXML extension is the quickest way to read and edit XML documents. Instead of walking a node tree by hand, SimpleXML turns the whole document into a regular PHP object whose elements you reach with familiar property and array syntax — $xml->title, $xml->item[0], $xml['id'].
This chapter covers the two functions you use to load XML — simplexml_load_file() (for a file or URL) and simplexml_load_string() (for XML you already hold as a string) — and then how to read elements, read attributes, loop over repeated nodes, add new data, and serialize the result back to XML.
SimpleXML ships with the standard PHP distribution and is enabled by default, so there is usually nothing to install.
When to use SimpleXML (and when not to)
- Use SimpleXML for reading and lightly editing well-formed XML: config files, RSS/Atom feeds, simple API responses, sitemaps.
- Reach for DOMDocument when you need fine-grained control: inserting nodes at a specific position, working with comments, or schema validation.
- Use the XML Parser (Expat) for very large documents that you want to stream event-by-event without loading everything into memory.
Loading XML data
The first step is to get the XML into a SimpleXML object. There are two entry points, and which one you pick depends only on where your XML currently lives.
Loading an XML file with simplexml_load_file()
simplexml_load_file() reads XML from a local path or a URL and returns a SimpleXMLElement. On a parse error it returns false and emits a warning.
<?php
// books.xml on disk, or "https://example.com/feed.xml"
$xml = simplexml_load_file('books.xml');
if ($xml === false) {
echo "Failed to load XML.";
} else {
echo $xml->book[0]->title; // first <title>
}Loading an XML string with simplexml_load_string()
When the XML is already in a variable — for example the body of an HTTP response — use simplexml_load_string() instead.
Both functions return the document's root element, not a wrapper around it. So in the example above $xml is <root>, and $xml->child is the <child> node inside it.
Tip: a
SimpleXMLElementholds a string-like value but is still an object. Wrap it in(string)(or concatenate it) whenever you need a plain PHP string — for example$title = (string) $xml->book[0]->title;. See convert SimpleXML to a string for details.
Accessing XML data
Once loaded, you read the document with object and array syntax.
Accessing elements
Child elements are object properties. When a tag repeats, index into it like an array; [0] is the first occurrence.
<?php
$data = <<<XML
<library>
<book><title>PHP Basics</title></book>
<book><title>Advanced XML</title></book>
</library>
XML;
$xml = simplexml_load_string($data);
echo $xml->book[0]->title, "\n"; // PHP Basics
echo $xml->book[1]->title, "\n"; // Advanced XMLLooping over repeated elements
Because repeated tags behave like an iterable list, foreach is the natural way to read all of them:
<?php
$data = <<<XML
<library>
<book><title>PHP Basics</title></book>
<book><title>Advanced XML</title></book>
</library>
XML;
$xml = simplexml_load_string($data);
foreach ($xml->book as $book) {
echo $book->title, "\n";
}
// PHP Basics
// Advanced XMLAccessing attributes
Attributes are reached with array syntax on the element that carries them:
<?php
$xml = simplexml_load_string('<book id="42" lang="en"><title>PHP</title></book>');
echo $xml['id'], "\n"; // 42
echo $xml['lang'], "\n"; // enModifying XML data
SimpleXML can also build and edit documents in place.
Adding elements
addChild() appends a new element and returns the element it created, so you can keep chaining:
<?php
$xml = simplexml_load_string('<root></root>');
$xml->addChild('child', 'Value');
echo $xml->child; // ValueAdding attributes
addAttribute() adds an attribute to whichever element you call it on:
<?php
$xml = simplexml_load_string('<root><child>Value</child></root>');
$xml->child->addAttribute('attribute', 'on');
echo $xml->child['attribute']; // onConverting SimpleXML back to XML
asXML() serializes the object back into an XML string (with no argument) or writes it straight to a file (when you pass a path). It's how you persist the changes you made above. See the asXML method for more.
<?php
$xml = simplexml_load_string('<root></root>');
$xml->addChild('child', 'Value');
echo $xml->asXML();
// <?xml version="1.0"?>
// <root><child>Value</child></root>Handling malformed XML
On failure these functions return false and trigger a warning, which is awkward to act on. Turn warnings into collectable errors with libxml_use_internal_errors():
<?php
libxml_use_internal_errors(true);
$xml = simplexml_load_string('<root><child></root>'); // missing </child>
if ($xml === false) {
foreach (libxml_get_errors() as $error) {
echo trim($error->message), "\n";
}
libxml_clear_errors();
}Conclusion
SimpleXML is the fastest path from an XML file or string to readable PHP data. Load with simplexml_load_file() or simplexml_load_string(), read elements and attributes with property and array syntax, loop repeated nodes with foreach, edit with addChild() and addAttribute(), and serialize back with asXML(). For heavier processing, move up to DOMDocument; for streaming huge files, use the XML Parser.