Software Development

How to Read and Write XML Documents using PHP DOM Extension


With XML Parser, you use can only read XML. To write and otherwise manipulate an XML document, you can use PHP DOM Extension. DOM stands for Document Object Model and it is a way of expressing XML nodes as a hierarchical tree of objects.


An XML document is read into memory as a tree of objects. Unlike with the XML Parser extension, the PHP DOM extension can traverse the tree in any directions to explore various elements, attributes, text nodes, and other nodes in the XML.  Nodes can be modified too.

Software Requirements

  • Windows 7 Professional SP1
  • PHP 5.5.9 / Zend Engine v2.5.0
  • NetBeans IDE 8.0.1
  • ApacheFriends XAMPP Version 1.8.3
    • ​Apache/2.4.7 (Win32) / Open SSL/1.0.1e

DOM Classes

Using DOM involves working with several built-in classes. The most common ones are the following:

  1. DOMNode
    This represents a single node in the DOM tree. Most DOM classes derive from DOMNode class.
  2. DOMDocument
    This represents the entire XML document in the form of a DOM tree stored in the memory. It derives from DMNode class, and is, the root of the tree.
  3. DOMElement
    This represents an element node.
  4. DOMAttr
    This represents an element’s attribute.
  5. DOMText
    This represents a plain-text node.
  6. DOMCharacterData
    This represents a CDATA (character data) node.

Working with DOM

Reading XML

The basic steps for reading XML documents are as follow:

  1. Create a DOMDocument object
  2. Read an XML String or load an XML file
  3. Traverse the content of the DOMDocument object using DOM-related properties and functions

Creating an XML Document

The basic steps for creating an XML document are as follow:


  1. Create an object of DOMDocument
  2. Build up the document
  3. Save or print the content of the XML document

Sample Output

You Might Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *