I'm trying to update a xml file of mine with php. I fugured out how to delete and add new elements, but I cant figure out how to update existing elements. I'v been using DOM for deleting and adding, but I can't get a hold of how to work with DOM replacechild. So this Is all I have now for my update code: $xdoc = new DomDocument; $xdoc->Load('myXML.xml'); // //Update the nodes in 'item' // $saveXML = $xdoc->save('myXML.xml'); return "Updated!"; PHP: This is my xml: <videos> <item> <question>What year is it?</question> <answers>2009/1985/2035/1745</answers> <url>312656</url> <position>2</position> </item> <item> <question>What's your name?</question> <answers>John/Lisa/Tomas/Sean</answers> <url>321546</url> <position>2</position> </item> </videos> Code (markup):
<?php $xml = <<<XML <?xml version="1.0"?> <root> <parent> <child>bar</child> <child>foo</child> </parent> </root> XML; $xml = <<<XML2 <?xml version="1.0"?> <videos> <item> <question>What year is it?</question> <answers>2009/1985/2035/1745</answers> <url>312656</url> <position>2</position> </item> <item> <question>What's your name?</question> <answers>John/Lisa/Tomas/Sean</answers> <url>321546</url> <position>2</position> </item> </videos> XML2; ?> <p> If we wanted to replace the entire <parent> node, we could do something like this: <?php // Create a new document fragment to hold the new <parent> node $parent = new DomDocument; $parent_node = $parent ->createElement('item'); // Add some children $parent_node->appendChild($parent->createElement('question', 'Today is')); $parent_node->appendChild($parent->createElement('answers', 'staurday')); $parent_node->appendChild($parent->createElement('url', 'foo')); $parent_node->appendChild($parent->createElement('position', '1')); // Add the keywordset into the new document // The $parent variable now holds the new node as a document fragment $parent->appendChild($parent_node); ?> <p> Next, we need to locate the old node: <?php // Load the XML $dom = new DomDocument; $dom->loadXML($xml); // Locate the old parent node $xpath = new DOMXpath($dom); $nodelist = $xpath->query('/videos/item'); $oldnode = $nodelist->item(0); ?> <p> We then import and replace the new node: <?php // Load the $parent document fragment into the current document $newnode = $dom->importNode($parent->documentElement, true); // Replace $oldnode->parentNode->replaceChild($newnode, $oldnode); // Display echo $dom->saveXML(); ?> PHP: This was taken from the PHP.net replaceChild manual page and modified to work with your data. output is kinda garbled due to lack of html formatting but its tested to work on WAMP ,Win XP.
Ok thanks. But I get an error on $oldnode = $nodelist->item(0); Call to a member function item() on a non-object in /hsphere... Any clues about that?