The DOMNode::replaceChild() function is an inbuilt function in PHP which is used replace the old child node with the passed new node. Further, if the new node is already a child it will not be added the second time. If the replacement succeeds the old node is returned.
Syntax:
php
Output:
php
Output:
DOMNode DOMNode::replaceChild( DOMNode $newnode, DOMNode $oldnode )Parameters: This function accept two parameters as mentioned above and described below:
- $newnode: It specifies the new node.
- $oldnode: It specifies the old node.
<?php
// Create a new DOMDocument instance
$document = new DOMDocument();
// Create a root element
$element = $document->appendChild(new DOMElement('root'));
// Create the text Node
$text1 = $document->createTextNode('Hello ! ');
$text2 = $document->createTextNode('Text to be replaced');
$text3 = $document->createTextNode('replaced');
// Append the nodes
$element->appendChild($text1);
$element->appendChild($text2);
// Replace the child
$element->replaceChild($text3, $text2);
// Render the output
echo $document->saveXML();
<?xml version="1.0"?> <root>Hello ! replaced</root>Example 2:
<?php
// Create a new DOMDocument instance
$document = new DOMDocument();
// Create a h1 element
$element = $document->appendChild(new DOMElement('h1'));
// Create the text Node
$text1 = $document->createTextNode('Geeksfor');
$text2 = $document->createTextNode('Text to be removed');
$text3 = $document->createTextNode('Geeks');
// Append the nodes
$element->appendChild($text1);
$element->appendChild($text2);
// Replace the child
$element->replaceChild($text3, $text2);
// Render the output
echo $document->saveXML();
?>
<?xml version="1.0"?> <root>GeeksforGeeks</root>Reference: https://www.php.net/manual/en/domnode.replacechild.php