<?php // This script performs the following actions: // 1) It reads the cd2catalog // 2) It uses an xpath query to locate the artist element for Bonnie Tyler // 3) It creates a new cd for Bonnie Tyler. The new cd only has // price and title elements. // 4) It adds the new cd to Bonnie Tyler's cd collection // 5) It changes the price element from its initial value of 6.0 to // a revised value of 5.0 $xmlDoc = new DOMDocument(); $xmlDoc->preserveWhiteSpace = false; $xmlDoc->load("cd2catalog.xml"); $root = $xmlDoc->documentElement; // create an xpath object and then query the artist elements for Bonnie Tyler $xpath = new DOMXPath($xmlDoc); $tyler = $xpath->evaluate('artist[name/last="Tyler" and name/first="Bonnie"]'); $tyler = $tyler->item(0); if (is_object($tyler)) { // create the cd element and its children elements $price = $xmlDoc->createElement('price', '6.0'); $title = $xmlDoc->createElement('title', "Total Eclipse of the Heart"); $cd = $xmlDoc->createElement('cd'); $cd->appendChild($price); $cd->appendChild($title); $tyler->appendChild($cd); } // change the price of the new cd from 6.0 to 5.0 $replace_price = $xmlDoc->createElement('price', '5.0'); $cd->replaceChild($replace_price, $price); // "save" the file--actually we should write the output of saveXML to a file $xmlDoc->formatOutput = true; print $xmlDoc->saveXML(); ?>