PHP XML DOM

to create a node, you call various methods of the domdocument class:

methoddescription
createelement()create an element node
createtextnode()creates a text node
createcdatasection()creates a character data node
createcomment()creates a comment node
    <?php            // create a domdocument object and set nice formatting
    
           $doc  = new domdocument( "1.0", "utf-8" );
           
           $doc->formatoutput = true ;
           
           //create the root  "stocklist" element
           
             $stocklist = $doc->createelement( "stocklist" );
             
             $doc->appendchild( $stocklist );
           
                  //create the first item element
                  
                  $item = $doc->createelement( "item" );
                  
                  $item->setattribute( "type", "fruit" );
                  
                  $stocklist->appendchild( $item );
                  
                  $name  = $doc->createelement( "name", "apple" );
                  
                  $item->appendchild( $name );
                  
                  $price = $doc->createelement( "price", "22.22" );
                  
                  $name->appendchild( $price );
                  
                  $quantity = $doc->createelement( "quantity", "222" );
                  
                  $name->appendChild( $quantity );                 
                  
                  //output the xml document 
                  
                  print $doc->savexml();                  
                                   
     ?>

the output of the code above will be:

     apple22.22222

removing Elements from a document

the domnode class removechild() method is used to remove an element node from xml document:

    <?php            // load the xml file 
       
                $doc = new DOMDocument;

                $doc->load('stocklist.xml');

                $stocklist = $doc->documentElement;
                
                var_dump($stocklist);

            // we retrieve the item and remove it from the stock
              
              $ss = $stocklist->getElementsByTagName('item')->item(0);
              
               $stocklist->removeChild($ss);
 
              echo $doc->savexml();
  ?>