I readed this DOMNode document and I found there isn't getelementsbytagname method in DOMNode. But, in my code I can use getelementsbytagname method with DOMNode. Can someone explain me why?
There is my code:
$dom = new DOMDocument;
@$dom->loadHTMLFile('http://www.poemjoy.com/show-8-27-1.html');
$xpath = new DOMXpath($dom);
$articles = $xpath->query('//div[@class="poem_detail"]');
foreach($articles as $tnode)
{
$ep=$tnode->getElementsByTagName('p');
}
The $tnode
is DOMNode type variable. I didn't find getelementsbytagname method in the document I mention before.Why can I use it?
Can someone please explain to me?
From the documentation you linked to in your question:
For clarification:
The assumingly 'discoverd' by previous posters and seemingly undocumented methods (.getElementsByTagName and .getAttribute) on this class (DOMNode) are in fact methods of the class DOMElement, which inherits from DOMNode.
i.e. $tnode
is a DOMElement
and not just a DOMNode
.
The specification of the DOM standard (which PHP implements) describes the permitted node types in a DOM document. These are:
Document, DocumentType, DocumentFragment, Element, Text, ProcessingInstruction, and Comment
It also notes that these elements are simply called nodes meaning that, strictly speaking, there is really no such thing as a DOMNode
but rather the DOMNode
is a general term used to talk about any one of those node types.
In your particular case (and as shown in the standard) getElementsByTagName
is only a member of Element
and Document
.
Since your selector is to select div
elements you are actually getting a NodeList of DOMElement
objects and not DOMNode
objects and you can use getElementsByTagName
. However this is dangerous because there is no guarantee that all your results will be DOMElement
objects, therefore it's good to typecheck before you use the function.