The DOM (Document Object Model) parser is a standard tree-based parser that allows you to load, manipulate, and generate XML data in a very strict, object-oriented way.
While SimpleXML is easier to write for basic read operations, the DOM parser is far more powerful when you need to create or modify advanced XML documents. If you have ever used JavaScript to manipulate HTML DOM elements, PHP's DOM parser will feel very familiar!
To use the DOM parser, we create a new DOMDocument object, load the XML string into it, and then traverse its children.
<?php
$xmlString = "
<bookstore>
<book>
<title>Learning PHP</title>
<author>John Doe</author>
</book>
</bookstore>";
// Initialize DOMDocument
$xmlDoc = new DOMDocument();
// Load the XML string
$xmlDoc->loadXML($xmlString);
// Extract elements by Tag Name
$titles = $xmlDoc->getElementsByTagName('title');
foreach ($titles as $title) {
// Output the text content inside the tag
echo "Book Title: " . $title->nodeValue . "\n";
}
?>
The DOMDocument class provides highly standardized methods like getElementsByTagName, createElement, and appendChild, giving you total programmatic control over your XML logic.
Which DOMDocument method is used to find elements based on their XML tag name?