Friday, September 5, 2025
HomeLanguagesPHP | DOMDocument createAttributeNS() Function

PHP | DOMDocument createAttributeNS() Function

The DOMDocument::createAttributeNS() function is an inbuilt function in PHP which is used to create a new attribute node with an associated namespace.

Syntax:

DOMAttr DOMDocument::createAttributeNS( string $namespaceURI, string $qualifiedName )

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

  • $namespaceURI: This parameter holds the URI of the namespace.
  • $qualifiedName This parameter holds the tag name and prefix of the attribute. For example: prefix:tagname.

Return Value: This function returns a new DOMAttr object on success or FALSE on failure.

Below program illustrates the DOMDocument::createAttributeNS() function in PHP:

Program:




<?php
  
// Store the XML document to the source
$source = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<root><contact><email>abc@geeksforgeeks.org</email>
<mobile>+91-987654321</mobile></contact></root>
XML;
  
// Create a new document
$domDocument = new DOMDocument( '1.0' );
  
// Load the XML file
$domDocument->loadXML( $source );
      
// Use createAttributeNS() function to create new attribute
// node with an associated namespace
$attrNS = $domDocument->createAttributeNS(
                '{namespace}', 'info:cont_info' );
  
// Create XML document and display it
echo $domDocument->saveXML() . "\n";
  
// Assign value to the createAttributeNS
  
$domDocument->getElementsByTagName( 'contact' )
            ->item(0)->appendChild( $attrNS );
      
// Create XML document and display it
print $domDocument->saveXML() . "\n";
      
?>


Output:

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:info="{namespace}">
    <contact>
        <email>abc@geeksforgeeks.org</email>
        <mobile>+91-987654321</mobile>
    </contact>
</root>

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:info="{namespace}">
    <contact info:cont_info=
        "https://www.geeksforgeeks.org/about/contact-us/">
        <email>abc@geeksforgeeks.org</email>
        <mobile>+91-987654321</mobile>
    </contact>
</root>

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

RELATED ARTICLES

Most Popular

Dominic
32269 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6636 POSTS0 COMMENTS
Nicole Veronica
11802 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11865 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7027 POSTS0 COMMENTS
Thapelo Manthata
6703 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS