The DOMDocument::createElementNS() function is an inbuilt function in PHP that is used to create a new element node with an associated namespace.
Syntax:
DOMElement DOMDocument::createElementNS( string $namespaceURI,
string $qualifiedName, string $value )
Parameters: This function accepts three parameters as mentioned above and described below:
- $namespaceURI: This parameter holds the URI of the namespace.
- $qualifiedName: This parameter holds the qualified name of the element, as prefix:tagname.
- $value: This parameter holds the value of the element. The default value of this parameter is empty or none, means an empty element created.
Return Value: This function returns the new DOMElement on success or FALSE on failure.
Below examples illustrate the DOMDocument::createElementNS() function in PHP:
Example 1:
<?php
// Create a new DOMDocument
$dom = new DOMDocument('1.0', 'utf-8');
// Use createElementNS() function to create new
// element node with an associated namespace
$element = $dom->createElementNS('https://www.geeksforgeeks.org/category/php/',
'php:function', 'Welcome to GeeksforGeeks');
// Append the child element
$dom->appendChild($element);
// Create XML document and display it
echo $dom->saveXML();
?>
Output:
<?xml version="1.0" encoding="utf-8"?>
<php:function xmlns:php="https://www.geeksforgeeks.org/category/php/">
Welcome to GeeksforGeeks
</php:function>Example 2:
<?php
// Create a new DOMDocument
$dom = new DOMDocument('1.0', 'utf-8');
// Use createElementNS() function to create new
// element node with an associated namespace
$element1 = $dom->createElementNS('https://www.geeksforgeeks.org/category/php/',
'organization:GeeksforGeeks', 'A computer science portal');
$element2 = $dom->createElementNS('https://www.geeks.org/html',
'php:link', 'Welcome to GeeksforGeeks');
$element3 = $dom->createElementNS('https://www.geeksforgeeks.org/given-the-following-sequence-of-values-inserted-into-a/',
'algo:link', 'Best coding platform');
// Append the child element
$dom->appendChild($element1);
$dom->appendChild($element2);
$dom->appendChild($element3);
// Create XML document and display it
echo $dom->saveXML();
?>
Output:
<?xml version="1.0" encoding="utf-8"?>
<organization:GeeksforGeeks xmlns:organization
="https://www.geeksforgeeks.org/category/php/">
A computer science portal
</organization:GeeksforGeeks>
<php:link xmlns:php="https://www.geeks.org/html">
Welcome to GeeksforGeeks
</php:link>
<algo:link xmlns:algo="https://www.geeksforgeeks.org/given-the-following-sequence-of-values-inserted-into-a/">
Best coding platform
</algo:link>Reference: https://www.php.net/manual/en/domdocument.createelementns.php