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


PHP DOMElement getElementsByTagNameNS()用法及代碼示例

DOMElement::getElementsByTagNameNS()函數是PHP中的內置函數,用於獲取具有給定localName和namespaceURI的所有後代元素。

用法:

DOMNodeList DOMElement::getElementsByTagNameNS( 
          string $namespaceURI, string $localName )

參數:該函數接受上述和以下所述的兩個參數:



  • $namespaceURI:它指定名稱空間URI。
  • $localName:它指定本地名稱。

返回值:此函數返回一個DOMNodeList值,該值包含在此元素樹的預遍曆中遇到的所有匹配元素的順序。

下麵給出的程序說明了PHP中的DOMElement::getElementsByTagNameNS()函數:

程序1:

<?php 
// Create a new DOMDocument 
$dom = new DOMDocument(); 
   
// Load the XML 
$dom->loadXML("<?xml version=\"1.0\"?> 
<root> 
    <div xmlns:x=\"my_namespace\"> 
        <x:h1 x:style=\"color:red;\"> 
            Hello, this is my red heading. 
        </x:h1> 
        <x:h1 x:style=\"color:green;\"> 
            Hello, this is my green heading. 
        </x:h1> 
        <x:h1 x:style=\"color:blue;\"> 
            Hello, this is my blue heading. 
        </x:h1> 
    </div> 
    <div xmlns:y=\"another_namespace\"> 
        <y:h1 y:style=\"color:red;\"> 
            Hello, this is my new red heading. 
        </y:h1> 
        <y:h1 y:style=\"color:green;\"> 
            Hello, this is my new green heading. 
        </y:h1> 
        <y:h1 y:style=\"color:blue;\"> 
            Hello, this is my new blue heading. 
        </y:h1> 
    </div> 
</root>"); 
   
// Get the elements with h1 tag from 
// specific namespace 
$nodeList = $dom->getElementsByTagNameNS( 
                    'my_namespace', 'h1'); 
  
foreach ($nodeList as $node) { 
    echo $node->getAttribute('x: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> 
    <div xmlns:x=\"my_namespace\"> 
        <x:p>HELLO.</x:p> 
        <x:p>NEW.</x:p> 
        <x:p>WORLD.</x:p> 
    </div> 
    <div xmlns:y=\"g4g_namespace\"> 
        <y:p>GEEKS</y:p> 
        <y:p>FOR</y:p> 
        <y:p>GEEKS</y:p> 
    </div> 
</root>"); 
   
// Get the elements 
$nodeList = $dom->getElementsByTagNameNS( 
                    'g4g_namespace', 'p'); 
  
foreach ($nodeList as $node) { 
    echo $node->textContent . '<br>'; 
} 
?>

輸出:

GEEKS
FOR
GEEKS

參考: https://www.php.net/manual/en/domelement.getelementsbytagnamens.php




相關用法


注:本文由純淨天空篩選整理自gurrrung大神的英文原創作品 PHP | DOMElement getElementsByTagNameNS() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。