Use the appendChild(), replaceChild(), and removeChild() methods from PHP's DOM extension:
- <?php
- // define XML data string
- $xmlData = <<< END
- <?xml version="1.0"?>
- <favorites>
- <pet>Humphrey Hippo</pet>
- <flavor>chocolate</flavor>
- <movie>Star Wars</movie>
- </favorites>
- END;
- // read XML data
- $xml = new DOMDocument();
- $xml->formatOutput = true; // format output
- $xml->preserveWhiteSpace = false; // discount whitespace
- $xml->loadXML($xmlData) or die("ERROR: ↩
- Cannot create DOMDocument object");
- // print the original XML tree
- echo "<xmp>OLD:/n" . $xml->saveXML() . "</xmp>";
- // get document element
- $root = $xml->documentElement;
- // add a node before <movie>
- $movie = $root->childNodes->item(2);
- $book = $xml->createElement("book");
- $root->insertBefore($book, $movie);
- $book->appendChild($xml->createTextNode("The Lord Of The Rings"));
- // add a node after <movie>
- $toy = $xml->createElement("toy");
- $toy->appendChild($xml->createTextNode("Stuffed bear"));
- $root->appendChild($toy);
- // replace <flavor> with <icecream> $flavour = $root->childNodes->item(1); $icecream = $xml->createElement("icecream");
- $icecream->appendChild($xml->createTextNode("strawberry")); $root->replaceChild($icecream, $flavour);
- // delete <movie>
- $movie = $root->childNodes->item(3);
- $root->removeChild($movie);
- // print the modified XML tree
- echo "<xmp>NEW:/n" . $xml->saveXML() . "</xmp>";
- ?>