Easy Tutorial
❮ Func Date Sunset Func Mysqli Fetch All ❯

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):

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:

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:


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.

❮ Func Date Sunset Func Mysqli Fetch All ❯