The DOMNode::insertBefore() function is an inbuilt function in PHP which is used to insert a new node before a certain another node.
Syntax:
php
Output:
Program 2:
php
Output:
Reference: https://www.php.net/manual/en/domnode.insertbefore.php
DOMNode DOMNode::insertBefore( DOMNode $newNode, DOMNode $refNode )Parameters:This function accepts two parameters as mentioned above and described below:
- $newNode: It specifies the new node.
- $refNode (Optional): It specifies the reference node. If not supplied, newnode is appended to the children.
<?php
// Create a new DOMDocument
$dom = new DOMDocument();
// Create a paragraph element
$p_element = $dom->createElement('p',
'This is the paragraph element!');
// Append the child
$dom->appendChild($p_element);
// Create a paragraph element
$h_element = $dom->createElement('h1',
'This is the heading element!');
// Insert heading before HTML
$dom->insertBefore($h_element, $p_element);
// Render the output
echo $dom->saveXML();
?>
<?xml version="1.0"?> <h1>This is the heading element!</h1> <p>This is the paragraph element!</p>
Program 2:
<?php
// Create a new DOMDocument
$dom = new DOMDocument();
// Create a paragraph element
$p_element = $dom->createElement('p',
'GeeksforGeeks, paragraph');
// Append the child
$dom->appendChild($p_element);
// Create a paragraph element
$h_element = $dom->createElement('h1',
'GeeksforGeeks, heading');
// When second argument is not provided
// It will appended to the child
$dom->insertBefore($h_element);
// Render the output
echo $dom->saveXML();
?>
<?xml version="1.0"?> <p>GeeksforGeeks, paragraph</p> <h1>GeeksforGeeks, heading</h1>
Reference: https://www.php.net/manual/en/domnode.insertbefore.php