HomeLanguagesPHP | DOMAttr __construct() Function

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:




<?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', 'neveropen');
  
// Set the attribute to the node
$attr = $element->setAttributeNode($domAttr);
  
// Display the XML document
echo $domDocument->saveXML(); 
  
?>


Output:

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

Program 2:




<?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', 'neveropen');
  
// 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', '[email protected]');
  
// Set the attribute to the node
$attr = $element->setAttributeNode($domAttr3);
   
// Display the XML document
echo $domDocument->saveXML(); 
   
?>


Output:

<?xml version="1.0" encoding="iso-8859-1"?>
<root Name="neveropen" Address="Noida" mail="[email protected]"/>

Reference: https://www.php.net/manual/en/domattr.construct.php

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32713 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7088 POSTS0 COMMENTS
Nicole Veronica
12228 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12310 POSTS0 COMMENTS
Shaida Kate Naidoo
7203 POSTS0 COMMENTS
Ted Musemwa
7470 POSTS0 COMMENTS
Thapelo Manthata
7189 POSTS0 COMMENTS
Umr Jansen
7171 POSTS0 COMMENTS