PHP | SimpleXMLElement addChild() Function

Pre-requisite: Read XML Basics

The SimpleXMLElement::addChild() function is an inbuilt function in PHP which is used to add a child in a SimpleXML object.

Syntax:



SimpleXMLElement SimpleXMLElement::addChild($name, $value, $namespace);

Parameter: This function accepts three parameters as mentioned above and described below:

  • $name: It is required parameter. It specifies the name of the child element to be added.
  • $value: It is optional parameter. It specifies the value of the child element to be added.
  • $namespace: It is optional parameter. It specifies namespace for the child element.

Return Value: It returns SimpleXMLElement object on successful child addition.

Note: This function is available for PHP 5.1.3 and newer version.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// Loading XML document to $user
  
$user = <<<XML
<user>
<username>user123</username>
<name>firstname lastname</name>
<phone>+91-9876543210</phone>
<detail>I am John Doe. Live in Kolkata, India.</detail>
</user>
XML;
  
// creating new SimpleXMLElement
// object from $user
$xml = new SimpleXMLElement($user);
  
// Adding child named "institution"
// and valued "geeksforgeeks"
$xml -> addChild("institution", "geeksforgeeks");
  
// Printing as XML
echo $xml->asXML();
  
echo $xml->asXML('savexmltofile.xml');
  
?>

chevron_right


Output:

user123 firstname lastname +91-9876543210 I am John Doe.
Live in Kolkata, India. geeksforgeeks 1

Saved XML file:

Reference: https://www.php.net/manual/en/simplexmlelement.addchild.php



My Personal Notes arrow_drop_up

I am a programmer by hobby

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.