i

PHP Tutorial

PHP XML DOM

DOM parser is another tree-based parser that is used to parse XML documents. This parser functions need to be installed as they are part of PHP core. The XML line Joy will be parsed by DOM as a tree structure in below way:

Level1: XML document

Level2: Root element:

Level 3: Text element: “Joy”

Let us take the same example of Reminder.xml for XML DOM parser.

$xmlDom = new DOMDocument();
$xmlDom->load("Reminder.xml");

print $xmlDom->saveXML();
?>

The above PHP code initialize, load the XML and output it as below:

Lindsi Sebastian Reminder Send me an update this weekend!

You can also loop through all elements of the note element we created in the starting of the XML code. It will initialize, load and loop through all elements.

$xmlDom = new DOMDocument();
$xmlDom->load("Reminder.xml");

$data = $xmlDom->documentElement;
foreach ($data->childNodes AS $item) {
  print $item->nodeName . " = " . $item->nodeValue . "
";
}
?>

Output of above code will be:

#text =
to = Lindsi
#text =
from = Sebastian
#text =
heading = Reminder
#text =
body = Send me an update this weekend!
#text =

In above example, there are few empty text nodes because, when XML generates, it creates white spaces between nodes and DOM treats them as normal elements that can sometime become an issue if you are not aware of them.