📜  PHP | DOMElement getElementsByTagName()函数

📅  最后修改于: 2022-05-13 01:56:30.906000             🧑  作者: Mango

PHP | DOMElement getElementsByTagName()函数

DOMElement::getElementsByTagName()函数是PHP中的一个内置函数,用于通过标记名获取元素。

句法:

DOMNodeList DOMElement::getElementsByTagName( string $name )

参数:此函数接受单个参数$name保存标签名称或使用 * 获取所有标签。

返回值:此函数返回一个 DOMNodeList 值,该值包含具有给定标记名称的所有后代元素,按照在此元素树的前序遍历中遇到它们的顺序。

下面的例子说明了PHP中的DOMElement::getElementsByTagName()函数

示例 1:

PHP
loadXML("


    
    

Hello, this is my red heading.

    

Hello, this is my green heading.

    

Hello, this is my blue heading.

    
");   // Save the XML $nodeList = $dom->getElementsByTagName('h1'); foreach ($nodeList as $node) {     // Get the attribute value of style     echo $node->getAttribute('style') . '
'; }   ?>


PHP
loadXML("


    
     

Hello, this is my first paragraph.

       

Hello, this is my second paragraph.

       

Hello, this is my third paragraph.

      
");   // Get the element by tagname $nodeList = $dom->getElementsByTagName('p');   foreach ($nodeList as $node) {     // Get the textContent     echo $node->textContent . '
'; } ?>


输出:

color:red;
color:green;
color:blue;

示例 2:

PHP

loadXML("


    
     

Hello, this is my first paragraph.

       

Hello, this is my second paragraph.

       

Hello, this is my third paragraph.

      
");   // Get the element by tagname $nodeList = $dom->getElementsByTagName('p');   foreach ($nodeList as $node) {     // Get the textContent     echo $node->textContent . '
'; } ?>

输出:

Hello, this is my first paragraph.
Hello, this is my second paragraph.
Hello, this is my third paragraph.

参考: https://www. PHP.net/manual/en/domelement.getelementsbytagname。 PHP