PHP DOM Parser
In this page:
$dom = new DOMDocument();
$dom->loadXML($xml_string); // or $dom->load("file.xml")
$nodes = $dom->getElementsByTagName("tag_name");
$value = $node->getAttribute("attribute_name");
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.
Example: Loading an XML Document into DOM
<?php
// Create a new `DOMDocument` instance, stored in `$dom`
$dom = new DOMDocument();
$dom->loadXML("<catalog><book>PHP Basics</book></catalog>");
// Print `get_class($dom)` to the output
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".
Example: Finding Elements by Tag Name
<?php
// Create a new `DOMDocument` instance, stored in `$dom`
$dom = new DOMDocument();
$dom->loadXML("<catalog><book>A</book><book>B</book></catalog>");
// Declare `$books`, set to `$dom->getElementsByTagName("book")`
$books = $dom->getElementsByTagName("book");
// Loop over `$books`, binding each item to `$book`
foreach ($books as $book) {
// Print `$book->nodeValue . "\n"` to the output
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.
Example: Reading Element Attributes
<?php
// Create a new `DOMDocument` instance, stored in `$dom`
$dom = new DOMDocument();
$dom->loadXML('<book id="1">PHP Basics</book>');
// Declare `$book`, set to `$dom->getElementsByTagName("book")->item(0)`
$book = $dom->getElementsByTagName("book")->item(0);
// Print `$book->getAttribute("id") . "\n"` to the output
echo $book->getAttribute("id") . "\n";
// Print a detailed dump (with types) of `$book->hasAttribute("author")`
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.
Example: Creating and Modifying XML with DOM
<?php
// Create a new `DOMDocument` instance, stored in `$dom`
$dom = new DOMDocument();
// Declare `$book`, set to `$dom->createElement("book", "PHP Basics")`
$book = $dom->createElement("book", "PHP Basics");
$book->setAttribute("id", "1");
$dom->appendChild($book);
// Print `$dom->saveXML()` to the output
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.
Example: Saving the Modified Document
<?php
// Create a new `DOMDocument` instance, stored in `$dom`
$dom = new DOMDocument();
// Declare `$book`, set to `$dom->createElement("book", "PHP Basics")`
$book = $dom->createElement("book", "PHP Basics");
$dom->appendChild($book);
$dom->save("output.xml");
// Print `file_get_contents("output.xml")` to the output
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