Skip to content
Related Articles

Related Articles

Improve Article

PHP | DOMNode hasAttributes() Function

  • Last Updated : 27 Feb, 2020

The DOMNode::hasAttributes() function is an inbuilt function in PHP which is used to check if a node has attributes or not.

Syntax:

bool DOMNode::hasAttributes( void )

Parameters: This function doesn’t accept any parameters.

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

Below examples illustrate the DOMNode::hasAttributes() function in PHP:



Example 1:




<?php
   
// Create a new DOMDocument
$dom = new DOMDocument();
    
// Create a paragraph element
$element = $dom->createElement('p',
      'This is the paragraph element!');
   
// Set the attribute
$element->setAttribute('id', 'my_id');
   
// Append the child
$dom->appendChild($element);
    
// 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.

Example 2:




<?php
  
// Create a new DOMDocument
$dom = new DOMDocument();
   
// Create a paragraph element
$element = $dom->createElement('p'
         'This is the paragraph element!');
  
// Set the attribute
$element->setAttribute('class', 'my_class');
  
// Append the child
$dom->appendChild($element);
   
// Get the elements
$nodeList = $dom->getElementsByTagName('p');
foreach ($nodeList as $node) {
    if(!$node->hasAttribute('id')) {
        echo "No, id attribute is not there.";
    }
}
?>

Output:

No, id attribute is not there.

Reference: https://www.php.net/manual/en/domnode.hasattributes.php




My Personal Notes arrow_drop_up
Recommended Articles
Page :