<?php // include xml lib include_once '../lib.xml.inc.php'; // create new xml object $xml = new XML(); // create xml element $root = $xml->createElement('xml'); $xml->appendChild($root); // create 1st item $item1 = $xml->createElement('item'); $item1->setAttribute('id', 'item1'); $item1->appendChild($xml->createTextNode('this is a text-node')); $root->appendChild($item1); // create 2nd item $item2 = $xml->createElement('item'); $item2->setAttribute('id', 'item2'); $item2->appendChild($xml->createTextNode('and here is another one')); $root->appendChild($item2); // create 3rd item $item3 = $xml->createElement('item'); $item3->setAttribute('id', 'item3'); $item3->appendChild($xml->createTextNode('this is the 3rd element')); $root->appendChild($item3); // create 4th item $item4 = $xml->createElement('item'); $item4->setAttribute('id', 'item4'); $item4->appendChild($xml->createTextNode('and this is the last item')); $root->appendChild($item4); // show the dom echo $xml->toString(1);
<?php // include xml lib include_once '../lib.xml.inc.php'; // define list $list = array(1 => 'this is a text-node', 'and here is another one', 'this is the 3rd element', 'and this is the final item!'); // create new xml object $xml = new XML(); // create xml element $root = $xml->createElement('xml'); $xml->appendChild($root); // loop through list foreach ($list as $i => $text) { // set name of variable variable $item = 'item' . $i; // create 'item' element ${$item} = $xml->createElement('item'); // set an attribute, called 'id' ${$item}->setAttribute('id', $item); // append a text-node to 'item' ${$item}->appendChild($xml->createTextNode($text)); // append the new item to the root element $root->appendChild(${$item}); } // show the dom echo $xml->toString(1);
<?php // include xml lib include_once '../lib.xml.inc.php'; // define a list $list = array('first in line', 'second in line', 'third in line', 'fourth in line', 'fifth in line'); // create empty xml dom object $xml = new XML(); // create a tree $refChild = null; $doc = $xml->createElement('document'); for ($i = 0; $i < count($list); $i++) { // create new child $child = 'node' . ($i + 1); ${$child} = $xml->createElement('text-node'); ${$child}->setAttribute('id', $child); ${$child}->appendChild($xml->createTextNode($list[$i])); // insert in tree & update refChild $refChild = $doc->insertBefore(${$child}, $refChild); } // append the created 'doc' element to the root $xml->appendChild($doc); // dump dom using toString echo $xml->toString(1);