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.
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- Illegal to have multiple roots (start tag in epilo
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
I know this is mostly an annoying IDE problem.
The reason is
$DOMNodeList->item(0)
witch returns a DOMNode ( or at least the IDE thinks so ).To fix this you will have to Extract out the
$DOMDocument->getElementsByTagName( $tagName )->item($index)
into a method of its own. In the DOCBlock you set the @return statement to DOMElement witch fixes the inspection problem.This Works at least in PHPStorm.
This is what I use in my project to minimize IDE warning.
You don't need to cast anything, just call the method:
And by the way,
DOMElement
is a subclass ofDOMNode
. If you were talking about aDOMNodeList
, then accessing the elements in such a list can be done, be either the method presented above, with aforeach()
loop, either by using theitem()
method ofDOMNodeList
: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:Then you will have a $element variable of the correct type and no complaints from PHPLint.