WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP XML DOM Parser


The worked in DOM parser makes it conceivable to process XML archives in PHP.


In this instructional exercise you investigation of DOM

The XML DOM Parser

The DOM parser is a tree-based parser.

Look at the accompanying XML report fraction:

<?xml version="1.0" encoding="UTF-8"?>
<from>Jani</from>

The DOM sees the XML above as a tree structure:

  • Level 1: XML Document
  • Level 2: Root component: <from>
  • Level 3: Text component: "Jani"

Installation

The DOM parser capacities are a piece of the PHP center. There is no establishment expected to utilize these functions.


An XML File

The XML record beneath will be utilized in our example:

<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't overlook me this weekend!</body>
</note>

Load and Output XML

We need to instate the XML parser, load the xml, and yield it:

Example

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");

print $xmlDoc->saveXML();
?>

The yield of the code above will be:

Tove Jani Reminder Don't overlook me this end of the week!

If you select "View source" in the program window, you will see the accompanying HTML:

<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't overlook me this weekend!</body>
</note>

The precedent above makes a DOMDocument-Object and loads the XML from "note.xml" into it.

Then the saveXML() work puts the interior XML archive into a string, so we can yield it.


Looping through XML

We need to instate the XML parser, load the XML, and circle through all components of the <note> element:

Example

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");

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

The yield of the code above will be:

#text =
to = Tove
#text =
from = Jani
#text =
heading = Reminder
#text =
body = Don't overlook me this weekend!
#text =