PHP | DOMElement hasAttribute() Function

The DOMElement::hasAttribute() function is an inbuilt function in PHP which is used to know whether attribute with a specific name exists as a member of the element.

Syntax:

bool DOMElement::hasAttribute( string $name )

Parameters: This function accepts a single parameter $name which holds the name of attribute.

Return Value: This function returns TRUE on success or FALSE on failure.

Below given programs illustrate the DOMElement::hasAttribute() function in PHP:



Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a new DOMDocument
$dom = new DOMDocument();
  
// Load the XML
$dom->loadXML("<?xml version=\"1.0\"?>
<root>
    <div>
        <!-- id attribute is there -->
        <p id=\"prog\"> HELLO </p>
    </div>
</root>");
  
// Get the elements
$nodeList = $dom->getElementsByTagName('p');
  
foreach ($nodeList as $node) {
    if($node->hasAttribute('id')) {
        echo "Yes, id attribute is there.";
    }
}
?>

chevron_right


Output:

Yes, id attribute is there.

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a new DOMDocument
$dom = new DOMDocument();
  
// Load the XML
$dom->loadXML("<?xml version=\"1.0\"?>
<root>
    <div>
        <!-- id attribute is missing -->
        <p> HELLO </p>
    </div>
</root>");
  
// Get the elements
$nodeList = $dom->getElementsByTagName('p');
foreach ($nodeList as $node) {
    if(!$node->hasAttribute('id')) {
        echo "No, id attribute isn't there.";
    }
}
?>

chevron_right


Output:

No, id attribute isn't there.

Reference: https://www.php.net/manual/en/domelement.hasattribute.php




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.