PHP XML

This article explains how PHP works with XML, including XML parsers, SimpleXML parser, SimpleXML get methods, XML Expat parser, and DOM parser with practical examples.

Jun 10, 2026
PHP XML

PHP XML: Parsers, SimpleXML, Expat, and DOM Parser

XML is a markup language used to store and transfer structured data. Although JSON is very common in modern APIs, XML is still used in many systems, including legacy applications, RSS feeds, sitemap files, payment integrations, document formats, enterprise systems, and data exchange services.

PHP provides several ways to read and process XML data. The most common XML tools in PHP include SimpleXML, Expat parser, and DOM parser. Each parser has a different style and is useful in different situations.

This article explains the main PHP XML topics shown in the learning path: PHP XML parsers, PHP SimpleXML parser, PHP SimpleXML get, PHP XML Expat parser, and PHP DOM parser.

PHP XML Parsers

An XML parser is a tool that reads XML content and allows PHP to access the data inside it. Without a parser, XML is only plain text. The parser helps PHP understand the XML structure, elements, attributes, and text values.

A simple XML document may look like this:

<?xml version="1.0" encoding="UTF-8"?>
<book>
    <title>Learning PHP XML</title>
    <author>Adnan Mehrat</author>
    <year>2026</year>
</book>

This XML document contains a root element named book. Inside it, there are child elements: title, author, and year.

PHP can parse this XML using different parsers. The most common approaches are:

  • SimpleXML: easy to use and suitable for simple XML documents.

  • Expat parser: event-based parser useful for processing XML step by step.

  • DOM parser: loads XML into a document object model and allows advanced navigation and modification.

The best parser depends on the type and size of the XML document and what you need to do with it.

Why XML Is Used

XML is used to represent structured information in a readable format. It allows data to be organized using custom tags. Unlike HTML, XML does not have predefined display tags. Instead, developers define tags based on the data structure.

For example, a website sitemap is often written in XML. It may contain URLs, last modification dates, change frequency, and priority values.

<url>
    <loc>https://example.com/article</loc>
    <lastmod>2026-06-10</lastmod>
    <changefreq>weekly</changefreq>
</url>

PHP can read this XML and extract values such as the page URL and last modification date.

XML is also common in RSS feeds, SOAP APIs, configuration files, data exports, and old enterprise integrations. For this reason, learning XML parsing in PHP is still useful for backend developers.

PHP SimpleXML Parser

SimpleXML is one of the easiest ways to work with XML in PHP. It converts XML into an object-like structure, allowing developers to access XML elements using object syntax.

SimpleXML is useful when the XML structure is simple and predictable.

The following example loads XML from a string:

<?php
$xmlText = '
<book>
    <title>Learning PHP XML</title>
    <author>Adnan Mehrat</author>
    <year>2026</year>
</book>
';

$xml = simplexml_load_string($xmlText);

echo $xml->title;
echo $xml->author;
echo $xml->year;
?>

The simplexml_load_string() function reads XML from a string and returns a SimpleXML object.

If the XML is stored inside a file, you can use simplexml_load_file().

<?php
$xml = simplexml_load_file("book.xml");

echo $xml->title;
?>

SimpleXML is commonly used for reading RSS feeds, sitemap files, simple configuration files, and XML responses from external services.

Reading XML Elements with SimpleXML

SimpleXML makes it easy to read child elements. If an XML document contains multiple items, you can loop through them using foreach.

<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book>
        <title>PHP Basics</title>
        <author>Adnan</author>
    </book>
    <book>
        <title>PHP OOP</title>
        <author>Noor</author>
    </book>
</books>

You can read the books like this:

<?php
$xml = simplexml_load_file("books.xml");

foreach ($xml->book as $book) {
    echo $book->title;
    echo $book->author;
}
?>

This style is simple and readable, which makes SimpleXML a good choice for beginners.

PHP SimpleXML - Get

SimpleXML can also get attributes, element names, namespaces, and children. This is important because many XML documents store information inside attributes, not only inside elements.

For example, this XML uses attributes:

<books>
    <book id="1" category="programming">
        <title>PHP Basics</title>
    </book>
    <book id="2" category="web">
        <title>Laravel Guide</title>
    </book>
</books>

You can get attributes using the attributes() method.

<?php
$xml = simplexml_load_file("books.xml");

foreach ($xml->book as $book) {
    $attributes = $book->attributes();

    echo $attributes["id"];
    echo $attributes["category"];
    echo $book->title;
}
?>

SimpleXML also provides the children() method to get child elements.

<?php
$xml = simplexml_load_file("books.xml");

foreach ($xml->children() as $child) {
    echo $child->getName();
}
?>

The getName() method returns the name of the current XML element.

<?php
$xml = simplexml_load_string("<book><title>PHP XML</title></book>");

echo $xml->getName();
?>

Getting attributes, names, and children is useful when working with XML files where the structure contains metadata, IDs, categories, language codes, or custom attributes.

SimpleXML and Error Handling

When working with XML, the document may be invalid or broken. For this reason, it is important to handle parsing errors.

You can use libxml_use_internal_errors() to control XML errors manually.

<?php
libxml_use_internal_errors(true);

$xmlText = "<book><title>PHP XML</book>";

$xml = simplexml_load_string($xmlText);

if ($xml === false) {
    foreach (libxml_get_errors() as $error) {
        echo $error->message;
    }

    libxml_clear_errors();
} else {
    echo $xml->title;
}
?>

This helps prevent the application from showing raw parser warnings to users and allows developers to handle XML errors in a cleaner way.

PHP XML Expat Parser

The Expat parser is an event-based XML parser. This means it does not load the entire XML document into an object tree like SimpleXML or DOM. Instead, it reads the XML and triggers functions when it finds opening tags, closing tags, and text content.

Expat is useful when you want to process XML step by step. It can be helpful for larger XML files because it does not require working with the full document structure at once.

The Expat parser uses handler functions. These functions are called when specific XML events happen.

<?php
function startElement($parser, $name, $attributes) {
    echo "Start element: " . $name;
}

function endElement($parser, $name) {
    echo "End element: " . $name;
}

function characterData($parser, $data) {
    echo "Data: " . trim($data);
}

$xmlText = "
<book>
    <title>PHP XML</title>
    <author>Adnan</author>
</book>
";

$parser = xml_parser_create();

xml_set_element_handler($parser, "startElement", "endElement");
xml_set_character_data_handler($parser, "characterData");

xml_parse($parser, $xmlText);

xml_parser_free($parser);
?>

In this example, PHP calls startElement() when it finds an opening tag, endElement() when it finds a closing tag, and characterData() when it finds text content.

Expat is more complex than SimpleXML, but it gives more control over how XML is processed.

When to Use Expat Parser

The Expat parser can be useful when the XML file is large or when you want to process the document sequentially. Since it works as an event-based parser, it can avoid some memory usage problems that may happen when loading very large XML files into memory.

Possible use cases include:

  • Reading large XML exports.

  • Processing XML logs.

  • Parsing streamed XML data.

  • Extracting only specific elements from a large XML file.

  • Building custom XML processing logic.

For normal small XML files, SimpleXML is usually easier. For complex editing, DOM may be better. For event-based reading, Expat is useful.

PHP DOM Parser

The DOM parser loads XML into a document object model. This means the XML becomes a tree of nodes that PHP can navigate, read, modify, create, or delete.

DOM is more powerful than SimpleXML when you need advanced XML control. It is useful when editing XML documents or working with complex structures.

The following example loads XML using DOMDocument.

<?php
$xmlText = '
<book>
    <title>Learning PHP XML</title>
    <author>Adnan Mehrat</author>
</book>
';

$dom = new DOMDocument();

$dom->loadXML($xmlText);

$title = $dom->getElementsByTagName("title")->item(0)->nodeValue;

echo $title;
?>

The getElementsByTagName() method returns elements with a specific tag name. The nodeValue property returns the text value of the selected node.

DOM can also load XML from a file.

<?php
$dom = new DOMDocument();

$dom->load("book.xml");

echo $dom->getElementsByTagName("author")->item(0)->nodeValue;
?>

DOM is useful when you need detailed control over the XML tree.

Creating XML with DOM Parser

DOMDocument can also be used to create XML documents. This is useful when your application needs to generate XML output, such as sitemaps, feeds, exports, or integration files.

<?php
$dom = new DOMDocument("1.0", "UTF-8");
$dom->formatOutput = true;

$book = $dom->createElement("book");

$title = $dom->createElement("title", "PHP XML Guide");
$author = $dom->createElement("author", "Adnan Mehrat");

$book->appendChild($title);
$book->appendChild($author);

$dom->appendChild($book);

echo $dom->saveXML();
?>

This code creates an XML document using PHP instead of writing XML manually as a string.

Using DOM to generate XML is safer and cleaner when the document structure is complex.

Modifying XML with DOM Parser

The DOM parser can modify existing XML documents. You can change node values, add new elements, remove elements, and save the updated XML.

<?php
$dom = new DOMDocument();
$dom->load("book.xml");

$title = $dom->getElementsByTagName("title")->item(0);
$title->nodeValue = "Updated PHP XML Guide";

$dom->save("book.xml");
?>

You can also add a new element.

<?php
$dom = new DOMDocument();
$dom->load("book.xml");

$book = $dom->getElementsByTagName("book")->item(0);

$year = $dom->createElement("year", "2026");

$book->appendChild($year);

$dom->save("book.xml");
?>

This makes DOM useful when PHP needs to update XML configuration files, generate XML exports, or change XML documents programmatically.

SimpleXML vs Expat vs DOM

PHP provides more than one XML parser because different projects need different approaches.

SimpleXML is best when the XML structure is simple and you only need to read values easily. It is beginner-friendly and requires less code.

Expat is best when you want event-based parsing or when you need to process XML step by step. It can be useful for large XML documents or streaming-style processing.

DOM is best when you need advanced control over the XML document. It can read, create, edit, and save XML using a tree structure.

A practical comparison:

  • Use SimpleXML for RSS feeds, sitemaps, simple XML responses, and basic reading.

  • Use Expat for event-based parsing and large XML processing.

  • Use DOM for creating, editing, and deeply navigating XML documents.

Practical XML Example: Reading a Sitemap

A common real-world XML example is reading a sitemap file. A sitemap contains URLs that search engines can crawl.

<urlset>
    <url>
        <loc>https://example.com/</loc>
        <lastmod>2026-06-10</lastmod>
    </url>
    <url>
        <loc>https://example.com/blog</loc>
        <lastmod>2026-06-09</lastmod>
    </url>
</urlset>

You can read this sitemap with SimpleXML.

<?php
$xml = simplexml_load_file("sitemap.xml");

foreach ($xml->url as $url) {
    echo $url->loc;
    echo $url->lastmod;
}
?>

This example shows why SimpleXML is useful for simple structured files. It allows you to access XML elements in a clean and readable way.

Security Notes for PHP XML

When working with XML from external sources, security is important. XML may come from user uploads, third-party APIs, feeds, or external services.

Important security practices include:

  • Validate XML before processing it.

  • Handle parser errors safely.

  • Do not trust XML content from unknown sources.

  • Avoid displaying XML values without escaping them in HTML.

  • Be careful with very large XML files because they can consume memory.

  • Disable or avoid unsafe external entity processing when not needed.

If XML data will be shown inside an HTML page, escape the output using htmlspecialchars().

<?php
echo htmlspecialchars((string) $xml->title, ENT_QUOTES, "UTF-8");
?>

This helps prevent unsafe text from being interpreted as HTML or JavaScript.

Conclusion

PHP provides several useful tools for working with XML. SimpleXML is easy and practical for reading simple XML documents. Expat provides event-based parsing for step-by-step processing. DOMDocument provides advanced control for reading, creating, editing, and saving XML documents.

Understanding PHP XML parsers is useful for working with sitemaps, RSS feeds, XML APIs, exports, configuration files, and legacy systems. Even though JSON is very popular today, XML remains important in many real-world backend projects.

After learning XML parsing in PHP, the next step is to practice by reading RSS feeds, generating a sitemap, parsing XML API responses, and creating XML export files from database records.