25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

XML and Web Services ” 201<br />

As you can see, in this example we start by creating a book element and set its<br />

meta:isbn attribute with DomElement::setAttribute(). Next, we create a title element<br />

and a text node containing the book title, which is assigned to the title<br />

element using DomElement::appendChild(). For the author and pub:publisher elements,<br />

we again use DomDocument::createElement(), passing the node’s text contents<br />

as the second attribute. Finally, we append the entire structure to the<br />

DomDocument::documentElement property, which represents the root XML node;<br />

Moving Data<br />

Moving Data is not as obvious as you might expect, because the DOM extension<br />

doesn’t provide a method that takes care of that, explicitly. Instead, you use a combination<br />

of DomNode::appendChild() and DomNode::insertBefore().<br />

$dom = new DOMDocument();<br />

$dom->load("library.xml");<br />

$xpath = new DomXPath($dom);<br />

$xpath->registerNamespace("lib", "http://example.org/library");<br />

$result = $xpath->query("//lib:book");<br />

$result->item(1)->parentNode->insertBefore($result->item(1), $result->item(0));<br />

Here, we take the second book element and place it before the first. In the following<br />

example, on the other hand, we take the first book element and place it at the end:<br />

$dom = new DOMDocument();<br />

$dom->load("library.xml");<br />

$xpath = new DomXPath($dom);<br />

$xpath->registerNamespace("lib", "http://example.org/library");<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)<br />

$result = $xpath->query("//lib:book");<br />

$result->item(1)->parentNode->appendChild($result->item(0));<br />

DomNode::appendChild() and DomNode::insertBefore() will move the node to the new<br />

location. If you wish to duplicate a node, use “DomNode::cloneNode()” first:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!