LearnContact
Lesson 5520 min read

XML Handling

Learn how to read and navigate XML data in PHP using SimpleXML, and where DOMDocument fits in for more complex needs.

Introduction

Before JSON became the default, XML was the standard format for structured data on the web, and it is still very much alive today in legacy APIs, RSS/Atom feeds, and configuration files for various tools and services. Sooner or later, a PHP project will hand you a chunk of XML to parse.

This lesson covers PHP's SimpleXML extension, the easiest way to read XML data, and briefly introduces DOMDocument for when you need finer control.

What You Will Learn
  • What XML is and where it is still commonly used.
  • How to load XML with simplexml_load_string() and simplexml_load_file().
  • How to read elements and attributes from a SimpleXMLElement object.
  • When to reach for DOMDocument instead of SimpleXML.
  • How to parse a small XML snippet end to end.

What Is XML and Where Is It Still Used?

XML (Extensible Markup Language) represents structured data using nested, named tags, similar in spirit to HTML but designed for data rather than display. A piece of data is wrapped in an opening and closing tag, and tags can carry attributes as well as nested child elements.

example.xml
<user id="42">
    <name>Jane Doe</name>
    <email>jane@example.com</email>
</user>

Legacy APIs

Many older enterprise and government systems still expose XML-only APIs (like SOAP web services).

Data Feeds

RSS and Atom feeds — used for blog syndication and podcasts — are XML formats.

Configuration Files

Some build tools and frameworks (like Maven or certain .NET project files) use XML for configuration.

Document Formats

Formats like Microsoft Office's .docx and .xlsx are actually XML files inside a zip archive.

Reading XML with SimpleXML

PHP's SimpleXML extension turns an XML string into an object you can navigate almost like a regular PHP object, using -> to move between elements. Use simplexml_load_string() when the XML is already in a PHP string.

simplexml-string.php
<?php
$xmlString = '<user id="42">
    <name>Jane Doe</name>
    <email>jane@example.com</email>
</user>';

$user = simplexml_load_string($xmlString);

echo $user->name . "\n";
echo $user->email;
Output
Jane Doe
jane@example.com

simplexml_load_string() returns a SimpleXMLElement object on success, or false if the XML could not be parsed.

Accessing Elements and Attributes

Child elements are accessed as properties (->name), and repeated child elements become an iterable collection. Attributes are accessed by treating the element like an array.

elements-and-attributes.php
<?php
$xmlString = '<user id="42">
    <name>Jane Doe</name>
    <email>jane@example.com</email>
</user>';

$user = simplexml_load_string($xmlString);

// Attributes are accessed like array keys
echo "ID: " . $user["id"] . "\n";

// Elements are accessed like object properties
echo "Name: " . $user->name . "\n";
Output
ID: 42
Name: Jane Doe

When an element repeats — like multiple <item> tags inside a <items> parent — SimpleXML lets you loop over them directly with foreach.

looping-elements.php
<?php
$xmlString = '<library>
    <book><title>PHP Basics</title></book>
    <book><title>Learning SQL</title></book>
</library>';

$library = simplexml_load_string($xmlString);

foreach ($library->book as $book) {
    echo $book->title . "\n";
}
Output
PHP Basics
Learning SQL

Loading XML from a File

When the XML lives in a separate .xml file rather than a PHP string, use simplexml_load_file() instead, which reads the file directly.

load-from-file.php
<?php
$library = simplexml_load_file("catalog.xml");

if ($library === false) {
    echo "Failed to load or parse catalog.xml";
} else {
    foreach ($library->book as $book) {
        echo $book->title . "\n";
    }
}
Output (assuming catalog.xml exists and parses)
PHP Basics
Learning SQL

DOMDocument: A More Powerful Alternative

SimpleXML is great for quickly reading data, but it has limits: it is read-heavy, and modifying or building complex XML documents with it can get awkward. For more demanding work — creating new XML documents, using XPath queries, or manipulating a document's structure — PHP's DOMDocument class offers a fuller, more powerful API.

domdocument-preview.php
<?php
$dom = new DOMDocument();
$dom->loadXML('<user id="42"><name>Jane Doe</name></user>');

$nameNode = $dom->getElementsByTagName("name")->item(0);
echo $nameNode->textContent;
Output
Jane Doe
Which One Should You Use?

Reach for SimpleXML when you just need to read data quickly and the structure is simple. Reach for DOMDocument when you need to build, heavily modify, or query complex XML with XPath.

Example: Parsing an XML Snippet

Here is a complete, self-contained example: a small XML feed of articles, parsed and printed as a plain summary.

parse-feed.php
<?php
$feed = '<feed>
    <article id="1">
        <title>Getting Started with PHP</title>
        <author>Jane Doe</author>
    </article>
    <article id="2">
        <title>Understanding Arrays</title>
        <author>John Smith</author>
    </article>
</feed>';

$data = simplexml_load_string($feed);

if ($data === false) {
    echo "Could not parse feed.";
} else {
    foreach ($data->article as $article) {
        $id = $article["id"];
        echo "[$id] {$article->title} — by {$article->author}\n";
    }
}
Output
[1] Getting Started with PHP — by Jane Doe
[2] Understanding Arrays — by John Smith

Common Mistakes

Avoid These Mistakes
  • Forgetting that simplexml_load_string()/simplexml_load_file() return false (not an exception) on invalid XML.
  • Treating a SimpleXMLElement like a plain string in string-heavy operations without casting it with (string) first.
  • Trying to heavily restructure XML with SimpleXML when DOMDocument would be a far better fit.
  • Assuming every API you integrate with uses JSON — some legacy or enterprise systems still respond only in XML.

Best Practices

  • Always check for false after calling simplexml_load_string() or simplexml_load_file().
  • Cast SimpleXMLElement values to (string) or (int) when you need a plain scalar rather than an element object.
  • Use SimpleXML for quick reads; switch to DOMDocument for building or heavily manipulating XML.
  • When parsing XML from an external source, consider disabling external entity loading to avoid XXE-style security issues.

Frequently Asked Questions

Is XML still relevant if most modern APIs use JSON?

Yes — many legacy enterprise systems, SOAP web services, RSS/Atom feeds, and some document formats still rely on XML, so knowing how to read it remains useful.

What does simplexml_load_string() return on failure?

It returns the boolean false, so you should check the result before trying to use it as an object.

How do I access an XML attribute with SimpleXML?

Treat the element like an array, for example $element["id"], rather than using the -> property syntax used for child elements.

When should I use DOMDocument instead of SimpleXML?

Use DOMDocument when you need to build new XML documents, run XPath queries, or perform complex structural manipulation that SimpleXML does not support well.

Key Takeaways

  • XML is still used in legacy APIs, data feeds, and some configuration and document formats.
  • simplexml_load_string() and simplexml_load_file() turn XML into a navigable SimpleXMLElement object.
  • Child elements are accessed with -> and attributes are accessed like array keys.
  • DOMDocument offers a more powerful, if more verbose, API for building and heavily manipulating XML.
  • Always check for a false return value before using the parsed result.

Summary

XML may be older than JSON, but it remains a practical skill for PHP developers who work with legacy systems, feeds, or certain file formats. SimpleXML covers most everyday reading needs, while DOMDocument is there when you need more power.

Next, you will put both JSON and XML knowledge to work by learning how to consume external APIs directly from PHP.

Lesson 55 Completed
  • You understand what XML is and where it is still used.
  • You can parse XML with simplexml_load_string() and simplexml_load_file().
  • You can read elements and attributes from a SimpleXMLElement.
  • You know when to reach for DOMDocument instead of SimpleXML.
Next Lesson →

Working with APIs