Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

PHP XML DOM

The XML DOM Parser

The DOM parser is a tree-based parser.

Consider this fraction of an XML document:

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

The DOM represents the XML above as a tree structure:

  • Level 1: XML Document
  • Level 2: Root element: <from>
  • Level 3: Text content: “Jani”

Installation

The DOM parser functions are included in the PHP core, so no additional installation is required.

The XML File

The XML file below (“note.xml”) will be used in our example:

<?xml version=”1.0″ encoding=”UTF-8″?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don’t forget me this weekend!</body>
</note>

Load and Output XML

We aim to initialize the XML parser, load the XML file, and display its contents.

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

print $xmlDoc->saveXML();
?>

The result of the above code will be:

Tove Jani Reminder Don’t forget me this weekend!

Selecting “View source” in the browser will display the following HTML:

<?xml version=”1.0″ encoding=”UTF-8″?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don’t forget me this weekend!</body>
</note>

The example above creates a DOMDocument object, loads the XML from “note.xml” into it, and then uses the saveXML() function to convert the internal XML document into a string for output.

Looping through XML

We want to initialize the XML parser, load the XML, and iterate through all the elements within the <note> element.

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

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

The output of the code above will be:

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

In the example above, you’ll notice empty text nodes between each element. When XML is generated, it often includes white-spaces between nodes. The XML DOM parser treats these as regular elements, which can occasionally cause issues if you’re not aware of them.