Skip to content
Related Articles

Related Articles

Improve Article

PHP | DOMElement hasAttribute() Function

  • Last Updated : 05 Mar, 2020
Geek Week

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:




<?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.";
    }
}
?>

Output:

Yes, id attribute is there.

Program 2:




<?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.";
    }
}
?>

Output:

No, id attribute isn't there.

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :