PHP XML DOM
The built-in DOM parser makes it possible to process XML documents in PHP.
What is DOM?
The W3C DOM provides a standard set of objects for HTML and XML documents, and a standard interface for accessing and manipulating these documents.
The W3C DOM is divided into different parts (Core, XML, and HTML) and different levels (DOM Level 1/2/3):
Core DOM - Defines a standard set of objects for any structured document
XML DOM - Defines a standard set of objects for XML documents
HTML DOM - Defines a standard set of objects for HTML documents
To learn more about the XML DOM, visit our XML DOM Tutorial.
XML Parsing
To read and update - create and process - an XML document, you need an XML parser.
There are two basic types of XML parsers:
Tree-based parsers: These parsers convert the XML document into a tree structure. It analyzes the entire document and provides access to the elements of the tree, such as the Document Object Model (DOM).
Event-based parsers: These parsers view the XML document as a series of events. When a specific event occurs, the parser calls a function to handle it.
The DOM parser is a tree-based parser.
Consider the following XML document fragment:
The XML DOM views the above XML as a tree structure:
Level 1: XML Document
Level 2: Root element: <from>
Level 3: Text element: "Jani"
Installation
The DOM XML parser functions are part of the PHP core. There is no installation needed to use these functions.
XML File
The following XML file will be used in our examples:
Loading and Outputting XML
We need to initialize the XML parser, load the XML, and output it:
Example
The above code will output:
If you view the source code in the browser window, you will see the following HTML:
The above example creates a DOMDocument-Object and loads the XML from "note.xml" into this document object.
The saveXML() function places the internal XML document into a string, so we can output it.
Traversing XML
We need to initialize the XML parser, load the XML, and traverse all elements of the <note> element:
Example
The above code will output:
In the above example, you saw that there are empty text nodes between the elements.
When XML is generated, it usually contains whitespace between the nodes. The XML DOM parser treats them as regular elements, and if you're not aware of them, they can sometimes cause problems.
To learn more about the XML DOM, visit our XML DOM Tutorial.