Open In App

PHP | DOMElement hasAttributeNS() Function

Last Updated : 26 Feb, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
The DOMElement::hasAttributeNS() function is an inbuilt function in PHP which is used to know whether attribute in specific namespace named localName exists as a member of the element or not. Syntax:
bool DOMElement::hasAttributeNS( string $namespaceURI, string $localName )
Parameters: This function accepts two parameters as mentioned above and described below:
  • $namespaceURI: It specifies the namespace URI.
  • $localName: It specifies the local name.
Return Value: This function returns TRUE on success or FALSE on failure. Below examples illustrate the DOMElement::hasAttributeNS() function in PHP: Example 1: php
<?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";
?>
Output:
Yes, there are total of 3 style attributes inside my_namespace.
Example 2: php
<?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.";
?>
Output:
There are total of 0 id attributes inside another_namespace.
Reference: https://www.php.net/manual/en/domelement.hasattributens.php

Next Article

Similar Reads