Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP XML DOM

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, as well as standard interfaces 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 XML DOM, please 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.

Please look at the following XML document fragment:

Jani

XML DOM views the XML above as a tree structure:


Installation

The DOM XML parser functions are part of the PHP core. These functions can be used without installation.


XML file

The following XML file will be used in our examples:

Tove

Jani

Reminder

Don't forget me this weekend!

Load and Output XML

We need to initialize the XML parser, load the XML, and output it:

Example

load("note.xml"); print $xmlDoc->saveXML(); ?>

The above code will output:

ToveJaniReminder Don't forget me this weekend!

If you view the source code in the browser window, you will see the following HTML:

Tove

Jani

Reminder

Don't forget me this weekend!

The example above creates a DOMDocument object and loads the XML from "note.xml" into this document object.

The saveXML() function puts the internal XML document into a string so that we can output it.


Traverse XML

We need to initialize the XML parser, load the XML, and traverse all the elements of the element:

Example

load("note.xml"); $x = $xmlDoc->documentElement; foreach ($x->childNodes AS $item) {     print $item->nodeName . " = " . $item->nodeValue . "
"; } ?>

The above code will output:

#text =

to = Tove

#text =

from = Jani

#text =

heading = Reminder

#text =

body = Don't forget me this weekend!

#text =

In the example above, you saw empty text nodes between each element.

When XML is generated, it usually contains white space between nodes. The XML DOM parser treats them as normal elements, which can sometimes cause problems if you do not pay attention to them.


To learn more about XML DOM, please visit our XML DOM Tutorial.