<?php $xmlDoc = new DOMDocument(); $xmlDoc->preserveWhiteSpace = false; $xmlDoc->load("cd2catalog.xml"); $root = $xmlDoc->documentElement; // print the report header printf("%-25s %s\n", "Artist", "Avg Price"); // get the artist elements $artists = $root->getElementsByTagName('artist'); foreach ($artists as $artist) { // get the cds associated with this artist and compute their average price $cds = $artist->getElementsByTagName('cd'); $value = 0; $num_cds = 0; foreach ($cds as $cd) { $price = $cd->getElementsByTagName('price')->item(0); $value += $price->nodeValue; $num_cds++; } // create a properly formatted name: lastname, firstname $name = $artist->getElementsByTagName('name')->item(0); $firstname = $name->childNodes->item(0); $lastname = $name->childNodes->item(1); $formatted_name = $lastname->nodeValue . ", " . $firstname->nodeValue; printf("%-25s %6.2f\n", substr($formatted_name, 0, 25), $value / $num_cds); } ?>