HomeLanguagesPHP | DOMDocument createElement() Function

PHP | DOMDocument createElement() Function

The DOMDocument::createElement() function is an inbuilt function in PHP which is used to create a new instance of class DOMElement.

Syntax:

DOMElement DOMDocument::createElement( string $name, string $value )

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

  • $name: This parameter holds the tag name of the element.
  • $value: This parameter holds the value of the element. The default value of this function creates an empty element. The value of element can be set later using DOMElement::$nodeValue.

Return Value: This function returns a new instance of class DOMElement on success or FALSE on failure.

Below programs illustrate the DOMDocument::createElement() function in PHP:

Program 1:




<?php
  
// Create a new DOMDocument
$domDocument = new DOMDocument('1.0', 'iso-8859-1');
  
// Use createElement() function to add a new element node
$domElement = $domDocument->createElement('organization', 'neveropen');
  
// Append element to the document
$domDocument->appendChild($domElement);
  
// Save XML file and display it
echo $domDocument->saveXML();
  
?>


Output:

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

Program 2:




<?php
  
// Create a new DOMDocument
$domDocument = new DOMDocument('1.0', 'iso-8859-1');
  
// Use createElement() function to add a new element node
$domElement1 = $domDocument->createElement('organization');
$domElement2 = $domDocument->createElement('name', 'neveropen');
$domElement3 = $domDocument->createElement('address', 'Noida');
$domElement4 = $domDocument->createElement('email', '[email protected]');
  
// Append element to the document
$domDocument->appendChild($domElement1);
$domElement1->appendChild($domElement2);
$domElement1->appendChild($domElement3);
$domElement1->appendChild($domElement4);
  
// Save XML file and display it
echo $domDocument->saveXML();
  
?>


Output:

<?xml version="1.0" encoding="iso-8859-1"?>
<organization>
    <name>neveropen</name>
    <address>Noida</address>
    <email>[email protected]</email>
</organization>

Reference: https://www.php.net/manual/en/domdocument.createelement.php

RELATED ARTICLES

Most Popular

Dominic
32706 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7078 POSTS0 COMMENTS
Nicole Veronica
12215 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12305 POSTS0 COMMENTS
Shaida Kate Naidoo
7200 POSTS0 COMMENTS
Ted Musemwa
7458 POSTS0 COMMENTS
Thapelo Manthata
7179 POSTS0 COMMENTS
Umr Jansen
7164 POSTS0 COMMENTS