I prefer to use SimpleXML to parse XML in PHP:
PHP Code:
#!/usr/bin/php
<?PHP
function subnodes($xml, $name, $list = array())
{
foreach ($xml->children() as $element => $xmlnode)
if ($element == $name)
$list[] = $xmlnode;
else
$list = nodes($xmlnodes, $name, $list);
return $list;
}
for ($arg = 1; $arg < $argc; $arg++) {
$xml = @simplexml_load_file($argv[$arg]);
if ($xml === FALSE) {
fprintf(STDERR, "%s: Cannot load XML file.\n", $argv[$arg]);
exit(1);
}
for ($cat = 0; $xml->cat[$cat] !== NULL; $cat++) {
echo "cat ", $cat, ":\n";
foreach ($xml->cat[$cat]->item1 as $item1)
echo "\titem1: '", $item1, "'\n";
foreach ($xml->cat[$cat]->item2 as $item2)
echo "\titem2: '", $item2, "'\n";
foreach ($xml->cat[$cat]->item3 as $item3) {
echo "\titem3:\n";
foreach ($item3->description as $desc) {
echo "\t\tdescription:\n";
foreach ($desc->name as $name)
echo "\t\t\tname: '", $name, "'\n";
foreach ($desc->value as $value)
echo "\t\t\tvalue: '", $value, "'\n";
}
}
}
}
?>
Above,
$xml=simplexml_load_file(filename); loads the XML file or URL, yielding the root node in
$xml.
It is a DOM model, where
$xml->name is an array of
name nodes. When converted to or interpreted as a string, it yields the text that XML node (but not child nodes) contains.
In particular, the first name node in the first description node in the first item3 node of the first cat node is output by e.g.
PHP Code:
echo $xml->cat[0]->item3[0]->description[0]->name[0];
(which, as I wrote above, evaluates to the contents as a string, but is really an SimpleXMLElement object). Or, more verbosely,
PHP Code:
$cat = $xml->cat[0];
$item3 = $cat->item3[0];
$desc = $item3->description[0];
echo $desc->name[0];
You can use foreach() to loop over the arrays, just as I did in my PHP example code above.