HomeLanguagesPHP | DOMDocument importNode() Function

PHP | DOMDocument importNode() Function

The DOMDocument::importNode() function is an inbuilt function in PHP which is used to return a copy of the node which need to import and associates it with the current document.

Syntax:

DOMNode DOMDocument::importNode( DOMNode $importedNode, bool $deep = FALSE )

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

  • $importedNode: This parameter holds the node which need to import.
  • $deep: This parameter holds the Boolean value. If it set to TRUE then it will recursively import the subtree under the importedNode.

Return Value: This function returns the copied node on success or FALSE, if it cannot be copied.

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

Program:




<?php
  
// Create a new document
$dom = new DOMDocument;
  
// Load the XML document
$dom->loadXML("<root><contact><email>[email protected]</email>
<mobile>+91-987654321</mobile></contact></root>");
  
// Use getElementsByTagName() function to search
// all elements with given local tag name
$node = $dom->getElementsByTagName("contact")->item(0);
  
// Create a new document
$dom1 = new DOMDocument;
  
$dom1->formatOutput = true;
  
// Load the XML document
$dom1->loadXML("<root><contactinfo><email>[email protected]</email>
<mobile>+91-987654321</mobile></contactinfo></root>");
  
echo "Document before copying the nodes\n";
  
// Save the file in XML and display it
echo $dom1->saveXML();
  
// Use importNode() function to import the node
$node = $dom1->importNode($node, true);
  
// Append child to the document
$dom1->documentElement->appendChild($node);
  
echo "\nDocument after copying the nodes\n";
  
// Save XML document and display it
echo $dom1->saveXML();
  
?>


Output:

Document before copying the nodes
<?xml version="1.0"?>
<root>
    <contactinfo><email>[email protected]</email>
    <mobile>+91-987654321</mobile></contactinfo>
</root>
Document after copying the nodes
<?xml version="1.0"?>
<root>
    <contactinfo><email>[email protected]</email>
    <mobile>+91-987654321</mobile></contactinfo>
    <contact><email>[email protected]</email>
    <mobile>+91-987654321</mobile></contact>
</root>

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

RELATED ARTICLES

Most Popular

Dominic
32688 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7057 POSTS0 COMMENTS
Nicole Veronica
12198 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12293 POSTS0 COMMENTS
Shaida Kate Naidoo
7182 POSTS0 COMMENTS
Ted Musemwa
7447 POSTS0 COMMENTS
Thapelo Manthata
7160 POSTS0 COMMENTS
Umr Jansen
7150 POSTS0 COMMENTS