Take the 2-minute tour ×

This is my xml file. I want to insert-update data using the dom method in between the tags. I am a beginner in php and Xml technologies. I successfully created and read from this file but not been able to enter data in it using php.

The code for creating is as follows:-

  $ele = $doc->createElement( 'root' );
  $ele->nodeValue = $uvar;
  $doc->appendChild( $ele );
  $test = $doc->save("$id.xml");

The code for reading is as follows:-

  $xdoc = new DOMDocument( );
  $candidate = $xdoc->getElementsByTagName('root')->item(0);
  $newElement = $xdoc ->createElement('root');
  $txtNode = $xdoc ->createTextNode ($root);
  $newElement -> appendChild($txtNode);
  $candidate -> appendChild($newElement);
  $msg = $candidate->nodeValue;

Can someone help out with inserting and updating. Thank You!

share|improve this question
could you make your question more clear. Where are you getting your text to update your xml, or put your final XML structure. –  tsegay Dec 28 '10 at 23:58
add comment

2 Answers

Sometimes PHP + XML can be a bit uncomfortable. Most of the time I find this piece of code useful (rewritten a bit for your situation):

$array = array('anxmltag'=>'hello everybody','anothertag'=>'content','lasttag'=>'maybe');

$root = $doc->createElement('root');




You may want to expand this code to write second level XML tags.

share|improve this answer
add comment

i don't have much experience with the DOMDocument class, but it might be easier to work with a simpleXML object instead. it's a bit faster to pick up.


you can then just

$xml = new SimpleXMLElement('<root></root>');
$xml->addChild('test_node_name', 'value');
$xml->test_node_name = 'new_value';
echo $xml->test_node_name;

with this you treat multiple child elements that have the same name the same way you would treat an array so you can iterate through them, or access them by index. you can also create simplexml objects from files or strings. check it out.

share|improve this answer
add comment

Your Answer


