Home > Article > Backend Development > PHP XML DOM_PHP Tutorial
There are two basic types of XML parsers:
Tree-based parser: This parser converts XML documents into a tree structure. It analyzes the entire document and provides an API to access tree elements, such as text
Document Object Model (DOM).
Event-based parser: Treats an XML document as a series of events. When a specific event occurs, the parser calls a function to handle it.DOM parser is a tree-based parser.
DOM XML parser functions are an integral part of PHP core. No installation is required to use these functions.
XML file:
<?xml version="1.0" encoding="ISO-8859-1"?> <note> <to>George</to> <from>John</from> <heading>Reminder</heading> <body>Don't forget the meeting!</body> </note>
<?php $xmlDoc = new DOMDocument(); $xmlDoc->load("note.xml"); print $xmlDoc->saveXML(); ?>The saveXML() function puts the internal XML document into a string so we can output it.
Loop XML:
<?php $xmlDoc = new DOMDocument(); $xmlDoc->load("note.xml"); $x = $xmlDoc->documentElement; foreach ($x->childNodes AS $item) { print $item->nodeName . " = " . $item->nodeValue . "<br />"; } ?>When XML is generated, it will often contain whitespace between nodes. The XML DOM parser treats them as normal elements, which can sometimes cause problems if you don't pay attention to them.