当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


PHP DOMElement getElementsByTagName()用法及代码示例


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

用法:

DOMNodeList DOMElement::getElementsByTagName( string $name )

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


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

以下示例说明了PHP中的DOMElement::getElementsByTagName()函数:

范例1:

<?php 
  
// Create a new DOMDocument 
$dom = new DOMDocument(); 
  
// Load the XML 
$dom->loadXML("<?xml version=\"1.0\"?> 
<root> 
<body> 
    <div> 
    <h1 style=\"color:red;\"> Hello, this is my red heading. </h1> 
    <h1 style=\"color:green;\"> Hello, this is my green heading. </h1> 
    <h1 style=\"color:blue;\"> Hello, this is my blue heading. </h1> 
    </div> 
</body> 
</root>"); 
  
// Save the XML 
$nodeList = $dom->getElementsByTagName('h1'); 
foreach ($nodeList as $node) { 
    // Get the attribute value of style 
    echo $node->getAttribute('style') . '<br>'; 
} 
  
?>

输出:

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

范例2:

<?php 
  
// Create a new DOMDocument 
$dom = new DOMDocument(); 
  
// Load the XML 
$dom->loadXML("<?xml version=\"1.0\"?> 
<root> 
<body> 
    <div> 
    <p> Hello, this is my first paragraph. </p> 
    <p> Hello, this is my second paragraph. </p> 
    <p> Hello, this is my third paragraph. </p> 
    </div> 
</body> 
</root>"); 
  
// Get the element by tagname 
$nodeList = $dom->getElementsByTagName('p'); 
  
foreach ($nodeList as $node) { 
    // Get the textContent 
    echo $node->textContent . '<br>'; 
} 
?>

输出:

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



相关用法


注:本文由纯净天空筛选整理自gurrrung大神的英文原创作品 PHP | DOMElement getElementsByTagName() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。