Retro video games delivered to your door every month!
Click above to get retro games delivered to your door ever month!
DOM Functions

XXX. DOM Functions

Introduction

The DOM extension allows you to operate on XML documents through the DOM API with PHP 5.

For PHP 4, use DOM XML.

Installation

There is no installation needed to use these functions; they are part of the PHP core.

Predefined Classes

The API of the module follows the DOM Level 3 standard as closely as possible. Consequently, the API is fully object-oriented. It is a good idea to have the DOM standard available when using this module.

This module defines a number of classes, which are explained in the following tables. Classes with an equivalent in the DOM standard are named DOMxxx.

DOMAttr

Extends DOMNode. The DOMAttr interface represents an attribute in an DOMElement object.

Constructor

Methods

Properties

Table 1.

NameTypeRead-onlyDescription
namestringyesThe name of the attribute
ownerElementDOMElementyesThe element which contains the attribute
schemaTypeInfoboolyesNot implemented yet, always return NULL
specifiedboolyesNot implemented yet, always return NULL
valuestringnoThe value of the attribute

DOMCharacterData

Extends DOMNode.

Methods

Properties

Table 2.

NameTypeRead-onlyDescription
datastringnoThe contents of the node
lengthintyesThe length of the contents

DOMComment

Extends DOMCharacterData.

Constructor

DOMDocument

Extends DOMNode.

Constructor

Methods

Properties

Table 3.

NameTypeRead-onlyDescription
actualEncodingstringyes 
configDOMConfigurationyes 
doctypeDOMDocumentTypeyes The Document Type Declaration associated with this document.
documentElementDOMElementyes This is a convenience attribute that allows direct access to the child node that is the document element of the document.
documentURIstringno The location of the document or NULL if undefined.
encodingstringno 
formatOutputboolno 
implementationDOMImplementationyes The DOMImplementation object that handles this document.
preserveWhiteSpaceboolnoDo not remove redundant white space. Default to TRUE.
recoverboolno 
resolveExternalsboolno Set it to TRUE to load external entities from a doctype declaration. This is useful for including character entities in your XML document.
standaloneboolno 
strictErrorCheckingboolnoThrows DOMException on errors. Default to TRUE.
substituteEntitiesboolno 
validateOnParseboolnoLoads and validates against the DTD. Default to FALSE.
versionstringno 
xmlEncodingstringyes An attribute specifying, as part of the XML declaration, the encoding of this document. This is NULL when unspecified or when it is not known, such as when the Document was created in memory.
xmlStandaloneboolno An attribute specifying, as part of the XML declaration, whether this document is standalone. This is FALSE when unspecified.
xmlVersionstringno An attribute specifying, as part of the XML declaration, the version number of this document. If there is no declaration and if this document supports the "XML" feature, the value is "1.0".

DOMDocumentFragment

Extends DOMNode.

Methods

DOMDocumentType

Extends DOMNode

Each DOMDocument has a doctype attribute whose value is either NULL or a DOMDocumentType object.

Properties

Table 4.

NameTypeRead-onlyDescription
publicIdstringyesThe public identifier of the external subset.
systemIdstringyesThe system identifier of the external subset. This may be an absolute URI or not.
namestringyesThe name of DTD; i.e., the name immediately following the DOCTYPE keyword.
entitiesDOMNamedNodeMapyes A DOMNamedNodeMap containing the general entities, both external and internal, declared in the DTD.
notationsDOMNamedNodeMapyes A DOMNamedNodeMap containing the notations declared in the DTD.
internalSubsetstringyes The internal subset as a string, or null if there is none. This is does not contain the delimiting square brackets.

DOMElement

Extends DOMNode.

Constructor

Methods

Properties

Table 5.

NameTypeRead-onlyDescription
schemaTypeInfoboolyesNot implemented yet, always return NULL
tagNamestringyesThe element name

DOMEntity

Extends DOMNode

This interface represents a known entity, either parsed or unparsed, in an XML document.

Properties

Table 6.

NameTypeRead-onlyDescription
publicIdstringyes The public identifier associated with the entity if specified, and NULL otherwise.
systemIdstringyes The system identifier associated with the entity if specified, and NULL otherwise. This may be an absolute URI or not.
notationNamestringyes For unparsed entities, the name of the notation for the entity. For parsed entities, this is NULL.
actualEncodingstringno An attribute specifying the encoding used for this entity at the time of parsing, when it is an external parsed entity. This is NULL if it an entity from the internal subset or if it is not known.
encodingstringyes An attribute specifying, as part of the text declaration, the encoding of this entity, when it is an external parsed entity. This is NULL otherwise.
versionstringyes An attribute specifying, as part of the text declaration, the version number of this entity, when it is an external parsed entity. This is NULL otherwise.

DOMEntityReference

Extends DOMNode.

Constructor

DOMException

DOM operations raise exceptions under particular circumstances, i.e., when an operation is impossible to perform for logical reasons.

See also Chapter 20.

Properties

Table 7.

NameTypeRead-onlyDescription
codeintyesAn integer indicating the type of error generated

DOMImplementation

The DOMImplementation interface provides a number of methods for performing operations that are independent of any particular instance of the document object model.

Constructor

Methods

DOMNode

Methods

Properties

Table 8.

NameTypeRead-onlyDescription
nodeNamestringyesReturns the most accurate name for the current node type
nodeValuestringnoThe value of this node, depending on its type.
nodeTypeintyesGets the type of the node. One of the predefined XML_xxx_NODE constants
parentNodeDOMNodeyesThe parent of this node.
childNodesDOMNodeListyes A DOMNodeList that contains all children of this node. If there are no children, this is an empty DOMNodeList.
firstChildDOMNodeyes The first child of this node. If there is no such node, this returns NULL.
lastChildDOMNodeyes The last child of this node. If there is no such node, this returns NULL.
previousSiblingDOMNodeyes The node immediately preceding this node. If there is no such node, this returns NULL.
nextSiblingDOMNodeyes The node immediately following this node. If there is no such node, this returns NULL.
attributesDOMNamedNodeMapyes A DOMNamedNodeMap containing the attributes of this node (if it is a DOMElement) or NULL otherwise.
ownerDocumentDOMDocumentyes The DOMDocument object associated with this node.
namespaceURIstringyes The namespace URI of this node, or NULL if it is unspecified.
prefixstringno The namespace prefix of this node, or NULL if it is unspecified.
localNamestringyes Returns the local part of the qualified name of this node.
baseURIstringyes The absolute base URI of this node or NULL if the implementation wasn't able to obtain an absolute URI.
textContentstringno This attribute returns the text content of this node and its descendants.

DOMNodeList

Methods

Properties

Table 9.

NameTypeRead-onlyDescription
lengthintyes The number of nodes in the list. The range of valid child node indices is 0 to length - 1 inclusive.

DOMNotation

Extends DOMNode

Properties

Table 10.

NameTypeRead-onlyDescription
publicIdstringyes 
systemIdstringyes 

DOMProcessingInstruction

Extends DOMNode.

Constructor

Properties

Table 11.

NameTypeRead-onlyDescription
targetstringyes 
datastringno 

DOMText

Extends DOMCharacterData.

Constructor

Methods

Properties

Table 12.

NameTypeRead-onlyDescription
wholeTextstringyes 

DOMXPath

Constructor

Methods

Properties

Table 13.

NameTypeRead-onlyDescription
documentDOMDocument  

Examples

Many examples in this reference require an XML file. We will use book.xml that contains the following:

Example 1. book.xml

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
 "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" [
]>
<book id="listing">
 <title>My lists</title>
 <chapter id="books">
  <title>My books</title>
  <para>
   <informaltable>
    <tgroup cols="4">
     <thead>
      <row>
       <entry>Title</entry>
       <entry>Author</entry>
       <entry>Language</entry>
       <entry>ISBN</entry>
      </row>
     </thead>
     <tbody>
      <row>
       <entry>The Grapes of Wrath</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>0140186409</entry>
      </row>
      <row>
       <entry>The Pearl</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>014017737X</entry>
      </row>
      <row>
       <entry>Samarcande</entry>
       <entry>Amine Maalouf</entry>
       <entry>fr</entry>
       <entry>2253051209</entry>
      </row>
      <!-- TODO: I have a lot of remaining books to add.. -->
     </tbody>
    </tgroup>
   </informaltable>
  </para>
 </chapter>
</book>

Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Table 14. XML constants

ConstantValueDescription
XML_ELEMENT_NODE (integer) 1Node is a DOMElement
XML_ATTRIBUTE_NODE (integer) 2Node is a DOMAttr
XML_TEXT_NODE (integer) 3Node is a DOMText
XML_CDATA_SECTION_NODE (integer) 4Node is a DOMCharacterData
XML_ENTITY_REF_NODE (integer) 5Node is a DOMEntityReference
XML_ENTITY_NODE (integer) 6Node is a DOMEntity
XML_PI_NODE (integer) 7Node is a DOMProcessingInstruction
XML_COMMENT_NODE (integer) 8Node is a DOMComment
XML_DOCUMENT_NODE (integer) 9Node is a DOMDocument
XML_DOCUMENT_TYPE_NODE (integer) 10Node is a DOMDocumentType
XML_DOCUMENT_FRAG_NODE (integer) 11Node is a DOMDocumentFragment
XML_NOTATION_NODE (integer) 12Node is a DOMNotation
XML_HTML_DOCUMENT_NODE (integer) 13 
XML_DTD_NODE (integer) 14 
XML_ELEMENT_DECL_NODE (integer) 15 
XML_ATTRIBUTE_DECL_NODE (integer) 16 
XML_ENTITY_DECL_NODE (integer) 17 
XML_NAMESPACE_DECL_NODE (integer) 18 
XML_ATTRIBUTE_CDATA (integer) 1 
XML_ATTRIBUTE_ID (integer) 2 
XML_ATTRIBUTE_IDREF (integer) 3 
XML_ATTRIBUTE_IDREFS (integer) 4 
XML_ATTRIBUTE_ENTITY (integer) 5 
XML_ATTRIBUTE_NMTOKEN (integer) 7 
XML_ATTRIBUTE_NMTOKENS (integer) 8 
XML_ATTRIBUTE_ENUMERATION (integer) 9 
XML_ATTRIBUTE_NOTATION (integer) 10 

Table 15. DOMException constants

ConstantValueDescription
DOM_INDEX_SIZE_ERR (integer) 1 If index or size is negative, or greater than the allowed value.
DOMSTRING_SIZE_ERR (integer) 2 If the specified range of text does not fit into a DOMString.
DOM_HIERARCHY_REQUEST_ERR (integer) 3If any node is inserted somewhere it doesn't belong
DOM_WRONG_DOCUMENT_ERR (integer) 4 If a node is used in a different document than the one that created it.
DOM_INVALID_CHARACTER_ERR (integer) 5 If an invalid or illegal character is specified, such as in a name.
DOM_NO_DATA_ALLOWED_ERR (integer) 6 If data is specified for a node which does not support data.
DOM_NO_MODIFICATION_ALLOWED_ERR (integer) 7 If an attempt is made to modify an object where modifications are not allowed.
DOM_NOT_FOUND_ERR (integer) 8 If an attempt is made to reference a node in a context where it does not exist.
DOM_NOT_SUPPORTED_ERR (integer) 9 If the implementation does not support the requested type of object or operation.
DOM_INUSE_ATTRIBUTE_ERR (integer) 10 If an attempt is made to add an attribute that is already in use elsewhere.
DOM_INVALID_STATE_ERR (integer) 11 If an attempt is made to use an object that is not, or is no longer, usable.
DOM_SYNTAX_ERR (integer) 12If an invalid or illegal string is specified.
DOM_INVALID_MODIFICATION_ERR (integer) 13If an attempt is made to modify the type of the underlying object.
DOM_NAMESPACE_ERR (integer) 14 If an attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
DOM_INVALID_ACCESS_ERR (integer) 15 If a parameter or an operation is not supported by the underlying object.
DOM_VALIDATION_ERR (integer) 16 If a call to a method such as insertBefore or removeChild would make the Node invalid with respect to "partial validity", this exception would be raised and the operation would not be done.
Table of Contents
DOMAttr->__construct() --  Creates a new DOMAttr object
DOMAttr->isId() --  Checks if attribute is a defined ID
DOMCharacterData->appendData() --  Append the string to the end of the character data of the node
DOMCharacterData->deleteData() --  Remove a range of characters from the node
DOMCharacterData->insertData() --  Insert a string at the specified 16-bit unit offset
DOMCharacterData->replaceData() --  Replace a substring within the DOMCharacterData node
DOMCharacterData->substringData() --  Extracts a range of data from the node
DOMComment->__construct() --  Creates a new DOMComment object
DOMDocument->__construct() --  Creates a new DOMDocument object
DOMDocument->createAttribute() -- Create new attribute
DOMDocument->createAttributeNS() --  Create new attribute node with an associated namespace
DOMDocument->createCDATASection() -- Create new cdata node
DOMDocument->createComment() -- Create new comment node
DOMDocument->createDocumentFragment() -- Create new document fragment
DOMDocument->createElement() -- Create new element node
DOMDocument->createElementNS() --  Create new element node with an associated namespace
DOMDocument->createEntityReference() -- Create new entity reference node
DOMDocument->createProcessingInstruction() -- Creates new PI node
DOMDocument->createTextNode() -- Create new text node
DOMDocument->getElementById() -- Searches for an element with a certain id
DOMDocument->getElementsByTagName() -- Searches for all elements with given tag name
DOMDocument->getElementsByTagNameNS() --  Searches for all elements with given tag name in specified namespace
DOMDocument->importNode() -- Import node into current document
DOMDocument->load() --  Load XML from a file
DOMDocument->loadHTML() --  Load HTML from a string
DOMDocument->loadHTMLFile() --  Load HTML from a file
DOMDocument->loadXML() --  Load XML from a string
DOMDocument->normalizeDocument() -- Normalizes the document
DOMDocument->registerNodeClass() -- Register extended class used to create base node type
DOMDocument->relaxNGValidate() --  Performs relaxNG validation on the document
DOMDocument->relaxNGValidateSource() --  Performs relaxNG validation on the document
DOMDocument->save() --  Dumps the internal XML tree back into a file
DOMDocument->saveHTML() --  Dumps the internal document into a string using HTML formatting
DOMDocument->saveHTMLFile() --  Dumps the internal document into a file using HTML formatting
DOMDocument->saveXML() --  Dumps the internal XML tree back into a string
DOMDocument->schemaValidate() --  Validates a document based on a schema
DOMDocument->schemaValidateSource() --  Validates a document based on a schema
DOMDocument->validate() --  Validates the document based on its DTD
DOMDocument->xinclude() --  Substitutes XIncludes in a DOMDocument Object
DOMDocumentFragment->appendXML() -- Append raw XML data
DOMElement->__construct() --  Creates a new DOMElement object
DOMElement->getAttribute() -- Returns value of attribute
DOMElement->getAttributeNode() -- Returns attribute node
DOMElement->getAttributeNodeNS() --  Returns attribute node
DOMElement->getAttributeNS() -- Returns value of attribute
DOMElement->getElementsByTagName() -- Gets elements by tagname
DOMElement->getElementsByTagNameNS() -- Get elements by namespaceURI and localName
DOMElement->hasAttribute() -- Checks to see if attribute exists
DOMElement->hasAttributeNS() --  Checks to see if attribute exists
DOMElement->removeAttribute() -- Removes attribute
DOMElement->removeAttributeNode() -- Removes attribute
DOMElement->removeAttributeNS() -- Removes attribute
DOMElement->setAttribute() -- Adds new attribute
DOMElement->setAttributeNode() -- Adds new attribute node to element
DOMElement->setAttributeNodeNS() -- Adds new attribute node to element
DOMElement->setAttributeNS() -- Adds new attribute
DOMElement->setIdAttribute() -- Declares the attribute specified by name to be of type ID
DOMElement->setIdAttributeNode() -- Declares the attribute specified by node to be of type ID
DOMElement->setIdAttributeNS() -- Declares the attribute specified by local name and namespace URI to be of type ID
DOMEntityReference->__construct() --  Creates a new DOMEntityReference object
DOMImplementation->__construct() --  Creates a new DOMImplementation object
DOMImplementation->createDocument() --  Creates a DOMDocument object of the specified type with its document element
DOMImplementation->createDocumentType() --  Creates an empty DOMDocumentType object
DOMImplementation->hasFeature() --  Test if the DOM implementation implements a specific feature
DOMNamedNodeMap->getNamedItem() --  Retrieves a node specified by name
DOMNamedNodeMap->getNamedItemNS() --  Retrieves a node specified by local name and namespace URI
DOMNamedNodeMap->item() -- Retrieves a node specified by index
DOMNode->appendChild() --  Adds new child at the end of the children
DOMNode->cloneNode() --  Clones a node
DOMNode->hasAttributes() --  Checks if node has attributes
DOMNode->hasChildNodes() --  Checks if node has children
DOMNode->insertBefore() --  Adds a new child before a reference node
DOMNode->isDefaultNamespace() -- Checks if the specified namespaceURI is the default namespace or not
DOMNode->isSameNode() --  Indicates if two nodes are the same node
DOMNode->isSupported() --  Checks if feature is supported for specified version
DOMNode->lookupNamespaceURI() --  Gets the namespace URI of the node based on the prefix
DOMNode->lookupPrefix() --  Gets the namespace prefix of the node based on the namespace URI
DOMNode->normalize() --  Normalizes the node
DOMNode->removeChild() --  Removes child from list of children
DOMNode->replaceChild() --  Replaces a child
DOMNodelist->item() --  Retrieves a node specified by index
DOMProcessingInstruction->__construct() --  Creates a new DOMProcessingInstruction object
DOMText->__construct() --  Creates a new DOMText object
DOMText->isWhitespaceInElementContent() --  Indicates whether this text node contains whitespace
DOMText->splitText() --  Breaks this node into two nodes at the specified offset
DOMXPath->__construct() --  Creates a new DOMXPath object
DOMXPath->evaluate() --  Evaluates the given XPath expression and returns a typed result if possible.
DOMXPath->query() --  Evaluates the given XPath expression
DOMXPath->registerNamespace() --  Registers the namespace with the DOMXPath object
dom_import_simplexml --  Gets a DOMElement object from a SimpleXMLElement object