Using DOM to Read XML
The W3C’s Document Object Model (DOM) defines a unified way to access elements in an XML structure. Therefore, accessing elements in an HTML page using JavaScript’s DOM access and accessing elements in an XML file using PHP’s DOM access is quite similar.
Example: Using DOM to Read XML (from file or URL)
<?php $dom = new DOMDocument(); $dom->load('https://brainbell.com/feed'); foreach ($dom->getElementsByTagname('item') as $tags) { foreach (($tags->childNodes) as $tag) { if (is_a($tag, 'DOMElement')) { echo $tag->tagName . ':' . $tag->textContent ."<br>\n"; } } echo '<hr>'; }
Note that the listings use is_a()
so that the tag names are only evaluated in nodes of the type DOMElement
. This is because whitespace is considered as a DOM node (however, of type DOMText
).
Using DOM to Write XML
Apart from the read access, it is also possible to build complete XML documents from the ground up using PHP’s DOM support. This might look a bit clumsy; however, it works very well when you have to automatically parse a lot of data.
Example: Create XML File If Not Exists and Append Data
<?php $file = 'quotes.xml'; $dom = new DOMDocument(); //False means: remove the redundant whitespaces $dom->preserveWhiteSpace = false; //Format output with indentation and extra space $dom->formatOutput = true; //Create XML file if not exists if (! @$dom->load($file)) { $root = $dom->createElement('quotes'); $root = $dom->appendChild($root); $dom->save($file); } $quote = $dom->createElement('quote'); $quote->setAttribute('year', 2023); $coding = $dom->createElement('coding'); $coding->nodeValue = 'it is quote'; $author = $dom->createElement('author'); $author->nodeValue = 'brainbell'; $quote->appendChild($coding); $quote->appendChild($author); $dom->documentElement->appendChild($quote); $dom->save($file); echo 'Quote saved.';
The preceding code saves author, quote, and year in an XML document, appending to the data already there.
The quotes.xml
file contains the following data after executing the above code twice:
<?xml version="1.0"?> <quotes> <quote year="2023"> <coding>it is quote</coding> <author>brainbell</author> </quote> <quote year="2023"> <coding>it is quote</coding> <author>brainbell</author> </quote> </quotes>
Using XML: