Open In App

PHP | DOMNode hasAttributes() Function

Last Updated : 27 Feb, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads