Although the childNodes example on the previous page demonstrated how to traverse the children of a node, no practical information was returned. What would be far more useful in the case of our cd collection would be to return the id of each cd.
<cd id="0001">
The id data is contained in what is called an Attribute, according to the XML specification.
In DOMIT!, attributes are placed in an associative array named attributes.
The original method for accessing the attributes array was as a PHP associative array:
$myData = $myNode->attributes["id"];
However, a number of methods for the safe manipulation of the attributes array are now available,
and are the preferred means. These include:
getAttribute($name), which allows you to retrieve the value of the named attribute.
setAttribute($name, $value), which allows you to set the value of the named attribute.
removeAttribute($name), which removes the named attribute.
hasAttribute($name), which determines whether the named attribute exists.
We will therefore modify our childNodes loop from the previous page so that it echoes the id number of each cd rather than its tag name.
if ($cdCollection->documentElement->hasChildNodes()) {
$myChildNodes =& $cdCollection->documentElement->childNodes;
for ($i = 0; $i < count($myChildNodes); $i++) {
echo ("The id of child node $i is: " .
$myChildNodes[$i]->getAttribute("id") .
"\n");
}
}
The above example will return:
The id of child node 0 is: 0001
The id of child node 1 is: 0002
The id of child node 2 is: 0003
|