tags:

views:

1092

answers:

2

I want to convert a DOMNode object from a call to getElementsByTagName to a DOMElement in order to access methods like getElementsByTagName on the child element. In any other language, I would cast and it would be easy, but after some quick looking, PHP does not have object casting. So what I need to know is how to get a DOMElement object from a DOMNode object.

Thanks.

+5  A: 

You don't need to cast anything, just call the method:

$links = $dom->getElementsByTagName('a');

foreach ($links as $link) {
    $spans = $link->getElementsByTagName('span');
}

And by the way, DOMElement is a subclass of DOMNode. If you were talking about a DOMNodeList, then accessing the elements in such a list can be done, be either the method presented above, with a foreach loop, either by using the item() method of DOMNodeList

$link_0 = $dom->getElementsByTagName('a')->item(0);
Ionuț G. Stan
A: 

You don't need to do any explicit typecasting, just check if your DOMNode object has a nodeType of XML_ELEMENT_NODE.

PHP will be perfectly happy with this.

If you use PHPLint to check your code you will notice that PHPLint complains about using getElementsByTagName on a DOMNode object. To get around this you need to jump through the following hoop:

/*.object.*/ $obj = $node;
$element = /*.(DOMElement).*/ $obj;

Then you will have a $element variable of the correct type and no complaints from PHPLint.

Dominic Sayers