May 11, 2021 PHP
The built-in DOM parser makes it possible to work with XML documents in PHP.
W3C DOM provides a standard set of objects for HTML and XML documents, as well as a standard interface for accessing and operating those documents.
W3C DOM is divided into different sections (Core, XML and HTML) and different levels (DOM Level 1/2/3):
Core DOM - Define a standard set of objects for any structured document
XML DOM - Define a standard set of objects for XML documents
*
HTML DOM
- Defines a standard set of objects for HTML documents
To learn more about XML DOM, visit our
XML DOM tutorial.
To read and update - Create and process - an XML document, you need an XML parser.
There are two basic XML parser types:
The DOM parser is a tree-based parser.
Take a look at the following fragments of the XML documentation:
XML DOM treats the above XML as a tree structure:
DoM XML parser functions are part of the PHP core. You can use these functions without installation.
The following XML files will be applied in our example:
We need to initialize the XML parser, load the XML, and output it:
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");
print $xmlDoc->saveXML();
?>
The above code will output:
If you look at the source code in your browser window, you'll see the following HTML:
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
The instance above creates a DOMDocument-Object and loads the XML .xml "note" into the document object.
The saveXML() function puts the internal XML document into a string so that we can output it.
We're going to initialize the XML parser, load the XML, and traverse all the elements of the element:
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");
$x = $xmlDoc->documentElement;
foreach ($x->childNodes AS $item)
{
print $item->nodeName . " = " . $item->nodeValue . "<br>";
}
?>
The above code will output:
In the example above, you see an empty text node between each element.
When XML is generated, it usually contains white space between nodes. XML DOM parsers treat them as ordinary elements, and if you don't pay attention to them, sometimes there are problems.
To learn more about XML DOM, visit our XML DOM tutorial.
In the next section, we'll start with PHP SimpleXML.