Monday, November 18, 2024
Google search engine
HomeLanguagesPHP | DOMElement hasAttribute() Function

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:




<?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

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments