PHP | DOMNode appendChild() function
Last Updated :
19 Feb, 2020
The DOMNode::appendChild() function is an inbuilt function in PHP which is used to appends a child to an existing list of children or creates a new list of children. The child can be created with DOMDocument::createElement(), DOMDocument::createTextNode() or by using any other node.
Syntax:
DOMNode DOMNode::appendChild( DOMNode $newnode )
Parameters:This function accepts a single parameter $newnode which holds the node to append.
Return Value: This function returns the node which is added.
Exceptions: This function throws DOM_NO_MODIFICATION_ALLOWED_ERR, if the node is readonly or if the previous parent of the node being inserted is readonly or DOM_HIERARCHY_REQUEST_ERR, if the 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 or DOM_WRONG_DOCUMENT_ERR, if $newnode was created from a different document than the one that created this node.
Below given programs illustrate the DOMNode::appendChild() function in PHP:
Program 1:
<?php
$doc = new DOMDocument();
$node = $doc ->createElement( "em" , "GeeksforGeeks" );
$newnode = $doc ->appendChild( $node );
echo $doc ->saveXML();
?>
|
Output:
GeeksforGeeks
Program 2:
<?php
$doc = new DOMDocument();
$table = $doc ->createElement( "table" );
$tablenode = $doc ->appendChild( $table );
$tr = $doc ->createElement( "tr" );
$tablenode ->appendChild( $tr );
$th = $doc ->createElement( "th" , "Name" );
$th ->setAttribute( "style" , "border: 1px solid #dddddd;" );
$tr ->appendChild( $th );
$tr = $doc ->createElement( "tr" );
$tablenode ->appendChild( $tr );
$th = $doc ->createElement( "td" , "GeeksforGeeks" );
$th ->setAttribute( "style" , "background-color: #dddddd;border: 1px solid #dddddd;" );
$tr ->appendChild( $th );
echo $doc ->saveXML();
?>
|
Output:
Reference: https://www.php.net/manual/en/domnode.appendchild.php
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...