Skip to content
Tutorials Center
My learning

Topics

Lesson 69 of 147 ยท Working with Files

XML

Read, query and build XML in PHP with SimpleXML, DOMDocument, XPath and XMLWriter, parse HTML with PHP 8.4's Dom\HTMLDocument, and handle bad XML safely.

XML (Extensible Markup Language) is a text format for structured data built from nested, named elements, much like HTML but with tags you invent yourself. JSON has replaced it in most new web APIs, yet XML is everywhere you look in real projects: RSS and Atom feeds, sitemaps, SVG images, office documents (a .docx file is a zip of XML files), SOAP services, bank and invoice exchange formats, and countless configuration files.

PHP ships with several XML tools, and each one fits a different job. SimpleXML turns a document into objects you can walk with -> and [], which is perfect for reading. The DOM extension gives you the full W3C tree API for precise editing, and XPath lets you find nodes with short query strings. XMLWriter streams new documents out piece by piece. Since PHP 8.4 there is also Dom\HTMLDocument, a standards-compliant HTML5 parser with CSS selectors. This lesson tours all of them with runnable examples.

If you haven't read JSON yet, it's worth doing so first; many ideas (decoding text into PHP structures, handling errors, encoding back) carry over directly.

A quick look at XML

Here is the small document most examples below use: a bookshop catalog.

XML
<?xml version="1.0" encoding="UTF-8"?>
<catalog updated="2026-10-01">
  <book id="b1" lang="en">
    <title>The Quiet Compiler</title>
    <author>Mara Iliฤ‡</author>
    <price currency="EUR">24.50</price>
  </book>
  <book id="b2" lang="de">
    <title>Schnelle Schleifen</title>
    <author>Jonas Weber</author>
    <price currency="EUR">19.90</price>
  </book>
</catalog>

The vocabulary you need:

  • An element is a tag pair and everything inside it: <title>โ€ฆ</title>. Every document has exactly one root element (<catalog> here).
  • An attribute is a name="value" pair inside a start tag: id="b1".
  • Text content is the text between tags.
  • The first line is the XML declaration. It's optional, but it states the version and encoding.

XML is strict. Every start tag needs an end tag (or must self-close like <br/>), tags must nest properly, attribute values must be quoted, names are case-sensitive, and & and < in text must be written as &amp; and &lt;. A document that follows these rules is well-formed; a parser rejects anything else rather than guessing.

Reading XML with SimpleXML

simplexml_load_string() parses a string and returns a SimpleXMLElement for the root element (simplexml_load_file() does the same for a file path). Child elements become properties, repeated children can be looped over, and attributes are read like array keys:

PHP Reading a catalog with SimpleXML

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

A few things are worth noticing:

  • $catalog->book refers to all <book> children. foreach visits each one, count() counts them, and $catalog->book[0] picks one by position. Writing just $catalog->book->title means "the first book's title".
  • $book['id'] reads an attribute. $book->price['currency'] reads an attribute of a child element.
  • Every value is still a SimpleXMLElement, as the var_dump() shows. echo and string functions convert it automatically, but for numbers and comparisons cast explicitly: (float) $book->price, (string) $book->title. Comparing two elements with === or storing one as an array key without casting are classic SimpleXML bugs.

Missing elements don't raise errors in SimpleXML. $book->isbn on a book without <isbn> gives an empty element that casts to '', so a typo in a tag name silently produces empty output. Check with isset($book->isbn) when an element is optional.

Querying with XPath

Looping by hand gets tedious once documents grow. XPath is a small query language for XML trees, and SimpleXMLElement::xpath() runs a query and returns an array of matching elements:

XPath Selects
/catalog/book <book> children of the root <catalog>
//title every <title> anywhere in the document
//book[@lang="de"] books whose lang attribute is de
//book[price > 20]/title titles of books with a price above 20
//book/@id the id attributes themselves
//book[1] the first <book> among its siblings

SimpleXML can also change a document: assign to a child to replace its text, use addChild() and addAttribute() to grow the tree, and unset() to remove a node. asXML() turns the tree back into a string.

PHP XPath queries and editing with SimpleXML

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

array_map('strval', ...) converts each attribute node to a plain string, which is the usual way to get simple PHP values out of an XPath result.

Look at how the French title was added. Assigning to a property ($new->title = '...') creates the <title> child if it doesn't exist and escapes the text, so the & comes out as &amp;. The second argument of addChild() is not escaped the same way: it treats & as the start of an entity reference, so addChild('title', 'Pointeurs & Compagnie') loses the ampersand. Use addChild() values only for plain text you control, and assignment (or the DOM API below) for anything that came from users. Also notice the blank line where the removed book used to be: unset() removes the element but leaves the whitespace around it.

The DOM API

The DOM extension (DOMDocument) implements the same tree model browsers use for HTML: every element, attribute and text run is a node with a parent and children. It's more verbose than SimpleXML, but it can do everything: insert a node at an exact position, move nodes between documents, handle comments and processing instructions, and format output.

DOMXPath runs XPath queries against a DOMDocument. Its query() method returns a DOMNodeList, and evaluate() can also return numbers and strings directly, like count(//book) or sum(//price):

PHP DOMDocument and DOMXPath

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Some details from the example:

  • preserveWhiteSpace = false before loading, plus formatOutput = true before saving, gives you neatly indented output.
  • documentElement is the root element. firstElementChild skips any whitespace text nodes and returns the first real element.
  • Setting textContent escapes <, > and & correctly, so it's the safe way to put arbitrary text into a node.

SimpleXML and DOM can share a document: dom_import_simplexml() and simplexml_import_dom() convert between them without re-parsing, so you can read with SimpleXML and switch to DOM only for the one tricky edit.

Namespaces

Feeds, SVG and office formats put elements in namespaces, written as prefixes like <atom:link> bound to a URI with xmlns:atom="...". XPath can't see namespaced elements until you register a prefix: $xpath->registerNamespace('a', 'http://www.w3.org/2005/Atom'), then query //a:entry. With SimpleXML, call registerXPathNamespace() before xpath(), or use $element->children('http://www.w3.org/2005/Atom'). The prefix in your query doesn't need to match the document's; only the URI matters.

Parsing HTML with Dom\HTMLDocument (PHP 8.4)

DOMDocument::loadHTML() has been around for years, but it uses an old HTML 4 parser: it chokes on HTML5 tags like <main> and <section> with warnings, mangles UTF-8 unless you add tricks, and parses differently from browsers. PHP 8.4 added a new Dom namespace with Dom\HTMLDocument, which uses a real HTML5 parser (the same algorithm browsers follow) and supports CSS selectors through querySelector() and querySelectorAll():

PHP HTML5 parsing with Dom\HTMLDocument

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The paragraph with the links has no closing </p>, and the parser handles it exactly as a browser would, without any warnings. The accented "cafรฉ" survives too, because Dom\HTMLDocument treats input as UTF-8 by default. The nodes belong to new classes (Dom\HTMLElement instead of DOMElement), and the namespace also has Dom\XMLDocument for XML with the same modern API.

Scraping HTML is a common reason to reach for this class: pulling links, headings or prices out of pages. In a real script you'd load the page with Dom\HTMLDocument::createFromFile() or from a string you fetched. Our editor has no network access, so the examples use strings.

Writing XML with XMLWriter

To produce XML, you could build a DOM tree and call saveXML(). For large outputs such as a sitemap with 50,000 URLs or a product feed, XMLWriter is the better tool: it writes elements one after another and never holds the whole tree in memory. It also escapes text and attribute values for you, which string concatenation never does.

PHP Generating a sitemap with XMLWriter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The & in the third URL comes out as &amp;, exactly as the sitemap format requires. When writing to a file with openUri(), call flush() every few hundred elements to push the buffered output to disk.

Handling broken XML

By default, a parse failure prints a pile of warnings and the loader returns false. In real code you want to decide what happens. Call libxml_use_internal_errors(true) to collect the errors silently, check the return value, then read them with libxml_get_errors():

PHP Collecting XML parse errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The unquoted attribute value qty=3 makes the whole document invalid, so you get false and a precise line number instead of half a result. Always call libxml_clear_errors() after reading the errors, or they pile up for the next parse in the same script.

Untrusted XML and XXE

XML has a feature called external entities: a document can declare <!ENTITY x SYSTEM "file:///etc/passwd"> and ask the parser to paste that file's contents into the text. When a server parses XML uploaded by users with entity loading turned on, attackers can read local files or make the server send requests. This is the XXE (XML External Entity) attack.

Modern PHP is safe by default: since PHP 8.0 (with libxml2 2.9 or later), external entities are not loaded. Keep it that way. Never pass the LIBXML_NOENT or LIBXML_DTDLOAD flags when parsing data from outside your application; the name NOENT is misleading, since it actually turns entity substitution on. The secure coding checklist collects this rule with similar ones.

Which tool should you use?

Task Best fit
Read a feed, config file or API response SimpleXML (+ xpath())
Precise edits, inserting or moving nodes, namespaces-heavy formats DOMDocument + DOMXPath
Parse real-world HTML, use CSS selectors Dom\HTMLDocument (PHP 8.4+)
Produce large XML files XMLWriter
Read a huge XML file without loading it all XMLReader (a streaming, forward-only reader)

XMLReader is the mirror image of XMLWriter: it moves through a document one node at a time with read(), so it can process a multi-gigabyte export with constant memory. A common pattern is to stream to each <product> with XMLReader, then expand just that element into SimpleXML or DOM for convenient access.

A very common job for Dom\HTMLDocument is pulling data out of web pages: checking a site for broken links, building a link preview, collecting product images, or auditing pages for images without alt text. Finding the elements is the easy part. The tricky part is that the attribute values are usually relative: images/boots.webp, ../../products/ and / all mean different things depending on the address of the page they came from. You have to resolve each one against the page URL (or against the page's <base href>, if it has one) before you can use it.

PHP 8.5's URI extension does exactly this. Uri\WhatWg\Url::parse($href, $base) resolves a link the way browsers do, following the WHATWG URL standard, and returns null for input it can't parse. It also normalizes the result, so /products/ and ../../products/ both become the same absolute address and can be de-duplicated. The example below collects every web link and image from a page, skips mailto:, javascript: and links that only jump within the page, sorts links into internal and external ones, and reports images with missing alt text:

PHP Collecting links and images from a page

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Some details worth noticing:

  • resolve() keeps only http and https URLs and removes the #fragment, because page.html#top and page.html are the same page. The nullsafe operator ($url?->getScheme()) handles links that failed to parse.
  • getAttribute() returns null when an attribute is missing, and '' when it's present but empty. For alt, that difference matters: alt="" correctly marks a decorative image, while a missing alt is an accessibility bug.
  • srcset holds a comma-separated list of candidates, each a URL plus a width (800w) or density (2x) descriptor. Each URL needs resolving too.
  • The og:image meta tag is the picture social networks show when the page is shared, so link-preview tools read it first.
  • The second link to / is skipped because its resolved address was already seen.

On PHP versions before 8.5 there is no built-in resolver. Use a library from Composer for it; building one by hand with parse_url() takes a lot of code to get ../ segments, query strings and protocol-relative //host/ links right.

Fetching real pages politely

Our editor has no network access, so the example parses a string. In a real script you download the page first, with a timeout, an honest User-Agent that says who you are, and a check of the status code:

PHP
<?php

$context = stream_context_create(['http' => [
    'timeout' => 10,
    'user_agent' => 'LinkChecker/1.0 (+https://yoursite.example/bot)',
    'ignore_errors' => true,   // return the body for 404s too, so you can check the status
]]);

$html = file_get_contents($pageUrl, false, $context);
$status = http_get_last_response_headers()[0] ?? '';   // e.g. "HTTP/1.1 200 OK" (PHP 8.4+)

if ($html !== false && str_contains($status, ' 200 ')) {
    $doc = Dom\HTMLDocument::createFromString($html);
    // ... collect links and images as above
}

The cURL extension (see Calling other APIs from PHP) gives more control (redirect limits, compression, parallel requests) for bigger crawlers. Whatever you use, scrape responsibly: respect the site's robots.txt and terms of use, wait between requests instead of firing hundreds per second, cache what you download, and prefer an official API or feed when the site offers one. Scrapers also break whenever the site's HTML changes, so check that the elements you expect are there and fail loudly when they aren't.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In SimpleXML, how do you read the id attribute of a <book> element stored in $book?

    Attributes use array syntax in SimpleXML, while child elements use the arrow. $book->id would look for a child element named <id>.
  2. 2. Why should you write (float) $book->price instead of just $book->price when adding prices?

    Every value in a SimpleXML tree is a SimpleXMLElement. Echo converts it to a string automatically, but arithmetic, comparisons and array keys need an explicit cast to get a plain value.
  3. 3. Which XPath expression selects the titles of books whose lang attribute is en?

    The condition in square brackets applies to the book step, and @lang refers to an attribute. The first option would look for a lang attribute on the title elements.
  4. 4. You need to parse modern HTML5 pages and select elements with CSS selectors. Which class fits best?

    Dom\HTMLDocument (PHP 8.4) uses a standards-compliant HTML5 parser and offers querySelector() and querySelectorAll(). loadXML() would reject most real HTML because HTML isn't well-formed XML.
  5. 5. What does simplexml_load_string() return when the XML is not well-formed?

    The loader returns false. With libxml_use_internal_errors(true) you can then read the reasons and line numbers from libxml_get_errors().

Summary

  • XML is a strict, nested text format; parsers reject documents that aren't well-formed.
  • SimpleXML (simplexml_load_string/file) maps elements to -> properties and attributes to ['name']; cast values with (string), (int) or (float).
  • XPath finds nodes with paths and conditions like //book[@lang="de"]/title; use xpath() in SimpleXML or DOMXPath::query()/evaluate() with DOM.
  • DOMDocument gives full control over the tree: create, insert, move and format nodes. Setting textContent escapes text safely.
  • Dom\HTMLDocument (PHP 8.4) parses HTML5 like a browser and supports querySelector()/querySelectorAll().
  • XMLWriter streams new XML with automatic escaping; XMLReader streams huge documents in.
  • Use libxml_use_internal_errors(true) and libxml_get_errors() to handle bad input, and never enable entity loading (LIBXML_NOENT) for untrusted XML.

Next: Streams and Wrappers