The DOM parser is a tree-based parser.
Consider this fraction of an XML document:
<?xml version=”1.0″ encoding=”UTF-8″?> <from>Jani</from> |
The DOM represents the XML above as a tree structure:
<from>
The DOM parser functions are included in the PHP core, so no additional installation is required.
The XML file below (“note.xml”) will be used in our example:
<?xml version=”1.0″ encoding=”UTF-8″?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don’t forget me this weekend!</body> </note> |
We aim to initialize the XML parser, load the XML file, and display its contents.
<?php $xmlDoc = new DOMDocument(); $xmlDoc->load(“note.xml”); print $xmlDoc->saveXML(); ?> |
The result of the above code will be:
Tove Jani Reminder Don’t forget me this weekend! |
Selecting “View source” in the browser will display the following HTML:
<?xml version=”1.0″ encoding=”UTF-8″?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don’t forget me this weekend!</body> </note> |
The example above creates a DOMDocument
object, loads the XML from “note.xml” into it, and then uses the saveXML()
function to convert the internal XML document into a string for output.
We want to initialize the XML parser, load the XML, and iterate through all the elements within the <note>
element.
<?php $xmlDoc = new DOMDocument(); $xmlDoc->load(“note.xml”); $x = $xmlDoc->documentElement; foreach ($x->childNodes AS $item) { print $item->nodeName . ” = “ . $item->nodeValue . “<br>”; } ?> |
The output of the code above will be:
#text = to = Tove #text = from = Jani #text = heading = Reminder #text = body = Don’t forget me this weekend! #text = |
In the example above, you’ll notice empty text nodes between each element. When XML is generated, it often includes white-spaces between nodes. The XML DOM parser treats these as regular elements, which can occasionally cause issues if you’re not aware of them.