DOM-getelementsbytagname方法在DOMNode类中不存在

DOM-getelementsbytagname方法在DOMNode类中不存在

问题描述:

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?

我引用了这个 DOMNode 文档,我发现DOMNode中没有getelementsbytagname方法。 但是,在我的代码中,我可以使用带有DOMNode的getelementsbytagname方法。 有人可以解释一下原因吗? p>

我的代码是: p>

  $ 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'); 
  }  pre> 
 
 

$ tnode code>是DOMNode类型变量。 我之前提到的文件中没有找到getelementsbytagname方法。为什么可以 我用它吗? p>

有人可以向我解释一下吗? p> div>

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.

See: http://www.php.net/manual/en/class.domelement.php

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

Source

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.