XML Dom: Modifying Documents
PHP5 Dom allows you to add new data to a loaded document, this is done by useng
DomDocument::createElement();
DomDocument::createElementNS();
DomDocument::createTextNode();
Lets get down to Modifying XML Documents, this is one of the things i need to learn for the Zend PHP5 Certification never used DOM before.
In the example bellow we will add a new book to the libary.xml document:
$dom = new DomDocument(); //Create new DOM Object $dom->load(">createElement("book"); //Create a new "book" element $book->setAttribute("meta:isbn", "0973589825"); //Add meta ISBN number to the book element //---------- $title = $dom->createElement("title"); //Create a new element called title $text = $dom->createTextNode("php|architect’s Guide to PHP Design Patterns"); //Set out the Books Title $title->appendChild($text); //Attach the defined book title, to the new title element $book->appendChild($title); //Attach the new title element(now with a value) to the Book element created earlyer. //---------- $author = $dom->createElement("author","Jason E. Sweat"); //Create new author element $book->appendChild($author); //Attach new author element to the book element //---------- $publisher = $dom->createElement("pub:publisher", "Marco Tabini & Associates , Inc."); //Create a new publsher element $book->appendChild($publisher); //Attach new publisher element to the book element //---------- $dom->documentElement->appendChild($book);//Finaly the whole new book element with title, author and publisher needs attaching to the XML Dom object.
Follow the comments for basic analysis on what we did.
As you can see, in this example we start by creating a book element and set its meta:isbn attribute with DomElement::setAttribute().
Next, we create a title element and a text node containing the book title, which is assigned to the title element using DomElement::appendChild().
For the author and pub:publisher elements, we again use DomDocument::createElement(), passing the node’s text contents as the second attribute.
Finally, we append the entire structure to the DomDocument::documentElement property, which represents the root XML node;
No Comments »
RSS feed for comments on this post. TrackBack URL











