Results 1 to 2 of 2

Thread: add a new node to an existing xml

  1. #1
    Join Date
    Apr 2006
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default add a new node to an existing xml

    Hi,

    I need to add a new xml node to a exisiting xml. The xml is like this,


    Code:
    $xmlTmpl = '<template><item><id>0</id><name>pipe</name><description>blah, blah...</description><unit>m</unit></item><item><id>1</id><name>concrete</name><description>blah...</description><unit>t</unit></item></template>';
    I am using DOMElement to create a new xml element and the appendChild method to add this new node to the end of the xml
    as below.


    Code:
    		$doc = new DOMDocument();
    		$doc->loadXML($xmlTmpl);
    		$tmpl = $doc->documentElement;
    		$items = $tmpl->getElementsByTagName('item');
    
                    //create a new element
    		$itemid = $items->length;
    		$newItem = $doc->createElement('item');
    		$idNode = $doc->createElement('id',$itemid);
    		$nameNode = $doc->createElement('name', $name);
    		$dscpNode = $doc->createElement('description', $dscp);
    		$unitNode = $doc->createElement('unit', $unit);
    		$newItem->appendChild($idNode);
    		$newItem->appendChild($nameNode);
    		$newItem->appendChild($dscpNode);
    		$newItem->appendChild($unitNode);
    
                    //add the new element as a child of the xml root
    		$tmpl -> appendChild($newItem);
    
    		$xmlTmpl = $doc->saveXML();
    This snippet throws an error on me at line, $tmpl -> appendChild($newItem);. The error is,

    Only one top level element is allowed in an XML document. Error processing resource 'http://localhost/contest/getTemplate.php'. Line 6, Position 2

    Can anyone shed some lights? Many thanks.

  2. #2
    Join Date
    May 2006
    Posts
    41
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Arrow

    not sure . . . I am not to good with xml

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •