note 47540 deleted from ref.dom by didou

From: Date: Sat, 30 Dec 2006 02:53:42 +0000
Subject: note 47540 deleted from ref.dom by didou
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-121029@lists.php.net to get a copy of this message
Note Submitter: oliver dot christen at camptocamp dot com ---- simple exemple of how to get the value of an attribute, delete that attribute and create a new element at the place we want with the value of the attribute <?xml version="1.0"?> <book type="paperback"> <title name='MAP'>Red Nails</title> <price>$12.99</price> <author> <name first="Robert" middle="E" last="Howard"/> <birthdate>9/21/1977</birthdate> </author> </book> <?php //filename xml file to use $file = 'book.xml'; $doc = new domDocument; if (file_exists($file)) { $doc->load($file); } else { exit('Erreur !.'); } $xpath = new domXPath($doc); $query = "//author/*"; $xpathQuery = $xpath->query($query); // a for loop to iterate all the elements in the xpathQuery nodelist and allow us to find what we want // i could have used a while loop also, use what you prefer $size = $xpathQuery->length; for ($i=0; $i<$size; $i++){ $node = $xpathQuery->item($i); if ($node->nodeName == 'name' && $node->hasAttributes()){ foreach ($node->attributes as $attribute) { if ($attribute->name == 'last' && $attribute->value == 'Howard'){ foreach ($node->attributes as $attribute) { if ($attribute->name == 'first'){ // get first name value $firstname = $attribute->value; // we need the current node later so we know where to add the new element $refnode = $node; // remove the firstname attribut $node->removeAttribute('first'); } } } } } } if (isset($refnode)) { // we need the parent node (see below) $parentnode = $refnode->parentNode; // creat new element firstname $newnode = $doc->createElement('firstname', $firstname); // optional, creat a linebreak element $newtextnode = $doc->createTextNode(chr(10)); // insert the new element before the reference node (in this case, the 'name' node) $newnode = $parentnode->insertBefore($newnode, $refnode); // optional, insert the linebreak before the reference node, hence after the new 'firstname' element $newtextnode = $parentnode->insertBefore($newtextnode, $refnode); } print $doc->saveXML(); ?>

« previous php.notes (#121029) next »