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


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


DOMElement::hasAttributeNS()函數是PHP中的一個內置函數,用於了解名為localName的特定命名空間中的屬性是否作為元素的成員存在。

用法:

bool DOMElement::hasAttributeNS( string $namespaceURI, string $localName )

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


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

返回值:如果成功,則此函數返回TRUE;如果失敗,則返回FALSE。

以下示例說明了PHP中的DOMElement::hasAttributeNS()函數:

範例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> Hello, this is my new red heading. </y:h1> 
        <y:h1> Hello, this is my new green heading. </y:h1> 
        <y:h1> Hello, this is my new blue heading. </y:h1> 
    </div> 
</root>"); 
   
// Get the elements 
$nodeList = $dom->getElementsByTagName('h1'); 
   
$i = 0; 
   
foreach ($nodeList as $node) { 
    if($node->hasAttributeNS('my_namespace', 'style')) { 
        $i++; 
    } 
} 
echo "Yes, there are total of $i style  
               attributes inside my_namespace"; 
?>

輸出:

Yes, there are total of 3 style attributes inside my_namespace.

範例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:h1 x:id=\"color:red;\"> 1 </x:h1> 
        <x:h1 x:id=\"color:green;\"> 2 </x:h1> 
        <x:h1 x:id=\"color:blue;\"> 3 </x:h1> 
    </div> 
    <div xmlns:y=\"another_namespace\"> 
        <y:h1> 1 </y:h1> 
        <y:h1> 2 </y:h1> 
        <y:h1> 3 </y:h1> 
    </div> 
</root>"); 
  
// Get the elements 
$nodeList = $dom->getElementsByTagName('h1'); 
  
$i = 0; 
  
foreach ($nodeList as $node) { 
    if($node->hasAttributeNS('another_namespace', 'id')) { 
        $i++; 
    } 
} 
echo "There are total of $i id attributes 
                         inside another_namespace."; 
?>

輸出:

There are total of 0 id attributes inside another_namespace.

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



相關用法


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