The DOMNode::insertBefore() function is an inbuilt function in PHP which is used to insert a new node before a certain another node.
Syntax:
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.
Return Value: This function returns the inserted node.
Exceptions: This function throws DOM_NO_MODIFICATION_ALLOWED_ERR, if this node is readonly or if the previous parent of the node being inserted is readonly. DOM_HIERARCHY_REQUEST_ERR, if this node is of a type that does not allow children of the type of the $newNode node, or if the node to append is one of this node’s ancestors or this node itself, DOM_WRONG_DOCUMENT_ERR, if $newNode was created from a different document than the one that created this node, DOM_NOT_FOUND, if $refNode is not a child of this node.
Below given programs illustrate the DOMNode::insertBefore() function in PHP:
Program 1:
<?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();
?> |
Output:
<?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();
?> |
Output:
<?xml version="1.0"?> <p>GeeksforGeeks, paragraph</p> <h1>GeeksforGeeks, heading</h1>
Reference: https://www.php.net/manual/en/domnode.insertbefore.php