25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

XML and Web Services ” 195<br />

Modifying XML Documents<br />

Prior to <strong>PHP</strong> 5.1.3, SimpleXML had no means to add elements and attributes to<br />

an XML document. True, it was possible to change the values of attributes and<br />

elements, but the only way to add new children and attributes was to export the<br />

SimpleXMLElement object to DOM, add the elements and attributes using the latter,<br />

and then import document back into SimpleXML. Needless to say, this process was<br />

anything but simple. <strong>PHP</strong> 5.1.3, however, introduced two new methods to SimpleXML<br />

that now give it the power it needs to create and modify XML documents:<br />

SimpleXMLElement::addChild() and SimpleXMLElement::addAttribute().<br />

The addChild() method accepts three parameters, the first of which is the name<br />

of the new element. The second is an optional value for this element, and the third<br />

is an optional namespace to which the child belongs. Since the addChild() method<br />

returns a SimpleXMLElement object, you may store this object in a variable to which<br />

you can append its own children and attributes. The following example illustrates<br />

this concept:<br />

$book = $library->addChild(’book’);<br />

$book->addAttribute(’isbn’, ’0812550706’);<br />

$book->addChild(’title’, "Ender’s Game");<br />

$book->addChild(’author’, ’Orson Scott Card’);<br />

$book->addChild(’publisher’, ’Tor Science Fiction’);<br />

header(’Content-type: text/xml’);<br />

echo $library->asXML();<br />

This script adds a new “book” element to the $library object, thus creating a new<br />

object that we store in the $book variable so that we can add an attribute and three<br />

children to it. Finally, in order to display the modified XML document, the script calls<br />

the asXML() method of $library SimpleXMLElement. Before doing so, though, it sets a<br />

Content-type header to ensure that the client (a Web browser in this case) knows how<br />

to handle the content.<br />

Called without a parameter, the asXML() method returns an XML string. However<br />

asXML() also accepts a file path as a parameter, which will cause it to save the XML<br />

document to the given path and return a Boolean value to indicate the operation’s<br />

success.<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)

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

Saved successfully!

Ooh no, something went wrong!