duanchanguo7603 2018-05-01 16:18
浏览 243
已采纳

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?

  • 写回答

1条回答 默认 最新

  • douqianxun8540 2018-05-01 16:21
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥15 ensp路由器启动不了一直报#
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了