PHP DOM Parser
In this page:
Loading an XML Document into DOM
new DOMDocument() creates a new, empty DOM document object, and its load() method (for a file) or loadXML() method (for a string) parses XML content into that object's tree structure, ready for navigation or modification.
Note: Check the return value of load()/loadXML() (both return false on failure) before attempting to work with the document further.
Warning: DOM emits PHP warnings for malformed XML by default rather than throwing exceptions -- wrap loading in libxml_use_internal_errors(true) if you want to handle parse errors more gracefully.
Example: Loading an XML Document into DOM
<?php
$dom = new DOMDocument();
$dom->loadXML("<catalog><book>PHP Basics</book></catalog>");
echo get_class($dom);
?>
Login to try C/C++/Java/PHP code in the editor
Finding Elements by Tag Name
getElementsByTagName($tagName) searches the entire document for every element matching that tag name, anywhere in the tree, returning a DOMNodeList you can loop over -- similar in spirit to an XPath query, but simpler for the common case of "find all X".
Note: Use getElementsByTagName() as your default way to find every instance of a specific tag, regardless of how deeply nested it is in the document.
Warning: getElementsByTagName() searches the whole document by default when called on the DOMDocument itself, but searches only within a specific element's descendants when called on that element instead -- be clear about which scope you intend.
Example: Finding Elements by Tag Name
<?php
$dom = new DOMDocument();
$dom->loadXML("<catalog><book>A</book><book>B</book></catalog>");
$books = $dom->getElementsByTagName("book");
foreach ($books as $book) {
echo $book->nodeValue . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
Reading Element Attributes
A DOM element node's getAttribute($name) method reads a specific attribute's value directly, while hasAttribute($name) checks whether it exists at all -- straightforward, explicit methods for working with XML attributes in the DOM API.
Note: Check hasAttribute() first if an attribute might legitimately be missing, since getAttribute() on a missing attribute simply returns an empty string rather than null or an error.
Warning: getAttribute() returning an empty string is ambiguous between 'the attribute doesn't exist' and 'the attribute exists but is set to an empty string' -- use hasAttribute() when that distinction matters.
Example: Reading Element Attributes
<?php
$dom = new DOMDocument();
$dom->loadXML('<book id="1">PHP Basics</book>');
$book = $dom->getElementsByTagName("book")->item(0);
echo $book->getAttribute("id") . "\n";
var_dump($book->hasAttribute("author"));
?>
Login to try C/C++/Java/PHP code in the editor
Creating and Modifying XML with DOM
Unlike SimpleXML's more limited editing support, DOM offers a full set of methods for building an XML document from scratch: createElement() creates a new element, appendChild() attaches it to a parent, and setAttribute() adds an attribute -- letting you construct or modify a document programmatically.
Note: Build a new XML document by creating elements one at a time and appending them in the order you want them to appear, working from the root element downward.
Warning: A newly created element with createElement() exists only in memory until it is actually appended somewhere in the document tree with appendChild() -- creating it alone has no visible effect.
Example: Creating and Modifying XML with DOM
<?php
$dom = new DOMDocument();
$book = $dom->createElement("book", "PHP Basics");
$book->setAttribute("id", "1");
$dom->appendChild($book);
echo $dom->saveXML();
?>
Login to try C/C++/Java/PHP code in the editor
Saving the Modified Document
saveXML() returns the entire document (or a specific node) as an XML string, and save($filename) writes it directly to a file -- either way, changes made to the DOM tree only take effect in the actual output once one of these methods is called.
Note: Call saveXML() or save() as the final step after any DOM modifications, since the in-memory tree changes are invisible outside the script until then.
Warning: Modifying a DOM tree and forgetting to call saveXML() or save() afterward means the changes exist only in memory for the duration of the script and are never actually output or persisted.
Example: Saving the Modified Document
<?php
$dom = new DOMDocument();
$book = $dom->createElement("book", "PHP Basics");
$dom->appendChild($book);
$dom->save("output.xml");
echo file_get_contents("output.xml");
?>
Login to try C/C++/Java/PHP code in the editor
- Reaching for DOM when SimpleXML would be simpler and sufficient for a straightforward read-only parsing task -- DOM's extra power comes with noticeably more verbose code.
- Forgetting to call saveXML() (or save() for a file) after modifying a DOM document -- changes made to the in-memory tree do not automatically persist anywhere on their own.
- Confusing DOM's own node-tree navigation methods (childNodes, getElementsByTagName) with SimpleXML's simpler property-based access -- the two APIs are not interchangeable.
- DOMDocument::load() or loadXML() parses an XML file or string into a full DOM tree.
- getElementsByTagName() finds all elements with a given tag name anywhere in the document.
- DOM supports creating and modifying elements, then writing the changed document back out with saveXML() or save().
The DOM extension has been a core part of PHP since PHP 5 and is enabled by default in most standard installations.
Chapter Quiz — Complete all 24 topics to unlock
0/24 topics done
Complete these topics first:
- PHP Date & Time
- PHP Math Functions
- PHP JSON Handling
- PHP XML Handling
- PHP cURL Introduction
- PHP REST API Basics
- PHP Composer & Packages
- PHP Autoloading
- PHP Design Patterns
- PHP MVC Architecture
- PHP Security Best Practices
- PHP Performance Optimization
- PHP 8 New Features
- PHP Type Declarations
- PHP Match Expression Advanced
- PHP Fibers
- PHP Attributes
- PHP Magic Constants
- PHP Include & Require
- PHP Iterables
- PHP SimpleXML Parser
- PHP SimpleXML Get
- PHP XML Expat Parser
- PHP DOM Parser