Using DOMDocument in PHP

Introduction

In this article I will explain use of DOMDocument in PHP. The Document Object Model (DOM) has various node types. I will use DOM with simple XML but DOMDocument is a more powerful feature than simple XML. The DOM are XML_ELEMENT_NODE, XML_ATTRIBUTE_NODE, and XML_TEXT_NODE. DOM id depending on the node type. You can create DOM objects, such as:

$xml= new DomDocument();

You can load XML from a string with DOMDocument, file, or imported from a Simple XML object.

//Load XML from a string

$Dom_x->loadXML('The full of xml');

 

//Load XML from from a file

$Dom_x->load('pets.xml');

 

// imported from a Simplexml object

$Dom_e = dom_import_simplexml($simplexml);

$Dom_e = $Dom_x->importNode($Dom_e, true);

Example

Find elements with the DOM, such as:

<?php

error_reporting(E_ALL ^ E_NOTICE);

$Xml = <<<THE_XML

<Animal>

<dog>

<name>dogy</name>

<color>red</color>

<breed>hulu</breed>

</dog>

<cat>

<name>rocky</name>

<color>white</color>

<breed>tody</breed>

</cat>

<dog>

<name>jacky</name>

<color>black</color>

<breed>lab X</breed>

</dog>

</Animal>

THE_XML;

$Object = new DOMDocument();

$Object->loadXML($Xml);

$Path = new DOMXPath($Object);

$Name = $Path->query("*/name");

foreach ($Name as $element) {

$Parent = $element->parentNode->nodeName;

echo "$element->nodeValue ($Parent)<br/>";

}

?>

Output

cal2.jpg

Example

The element and attribute values can be searched with the DOM. For searching for a value I will use the attribute getNamedItem()->node value by id. Such as:

<?php

error_reporting(E_ALL);

$Xml = <<<THE_XML

<Animal>

<dog>

<name id="3">dogy</name>

<color>red</color>

<breed>hulu</breed>

</dog>

<cat>

<name id="4">rocky</name>

<color>white</color>

<breed>tody</breed>

</cat>

<dog>

<name id="3">jacky</name>

<color>black</color>

<breed>lab X</breed>

</dog>

</Animal>

THE_XML;

$Object = new DOMDocument();

$Object->loadXML($Xml);

$Path = new DOMXPath($Object);

$Result = $Path->query("dog/name[contains(., 'jacky')]");

foreach ($Result as $element) {

print $element->attributes->getNamedItem("id")->nodeValue;

}

?>

Output

dynamic check.jpg


Similar Articles