當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。