PHP | DOMAttr __construct() Function

The DOMAttr::__construct() function is an inbuilt function in PHP which is used to create a new DOMAttr object. This created object is a read-only type.

Syntax:

public DOMAttr::__construct( string $name, string $value )

Parameters: This function accepts two parameters as mentioned above and described below:

  • $name: This parameter holds the element name of the attribute.
  • $value: This parameter holds the value of the attribute.

Below programs illustrate the DOMAttr::__construct() function in PHP:

Program 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a new DOMDocument object
$domDocument = new DOMDocument('1.0', 'iso-8859-1');
  
// Create a root element
$rootElement = new DOMElement('root');
  
// Append the element as child element 
$element = $domDocument->appendChild($rootElement);
  
// Create an attribute
$domAttr = new DOMAttr('attr', 'GeeksforGeeks');
  
// Set the attribute to the node
$attr = $element->setAttributeNode($domAttr);
  
// Display the XML document
echo $domDocument->saveXML(); 
  
?>

chevron_right


Output:

<?xml version="1.0" encoding="iso-8859-1"?>
<root attr="GeeksforGeeks"/>

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
   
// Create a new DOMDocument object
$domDocument = new DOMDocument('1.0', 'iso-8859-1');
   
// Create a root element
$rootElement = new DOMElement('root');
  
// Append the element as child element
$element = $domDocument->appendChild($rootElement);
   
// Create an attribute
$domAttr1 = new DOMAttr('Name', 'GeeksforGeeks');
  
// Set the attribute to the node
$attr = $element->setAttributeNode($domAttr1);
   
// Create an attribute
$domAttr2 = new DOMAttr('Address', 'Noida');
  
// Set the attribute to the node
$attr = $element->setAttributeNode($domAttr2);
   
// Create an attribute
$domAttr3 = new DOMAttr('mail', 'abc@geeksforgeeks.org');
  
// Set the attribute to the node
$attr = $element->setAttributeNode($domAttr3);
   
// Display the XML document
echo $domDocument->saveXML(); 
   
?>

chevron_right


Output:

<?xml version="1.0" encoding="iso-8859-1"?>
<root Name="GeeksforGeeks" Address="Noida" mail="abc@geeksforgeeks.org"/>

Reference: https://www.php.net/manual/en/domattr.construct.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.