Inserting child element and data by addChild function

By using simpleXMLElement we can add child element to XML data structure. Here is an example. We have used our sample XML file for this.

xml-sample1.php

<?Php
require "xml-sample1.php";
$main1 = new SimpleXMLElement($str_xml);
$add=$main1->addChild('Job');
$add->addChild('designation','Manager');
echo $main1->asXML(); 
?>
In above code we have added one child element Job at root level and now let us try to add child element at lower node. Here is the code.
<?Php
require "xml-sample1.php";
$main1 = new SimpleXMLElement($str_xml);
$add=$main1->addChild('Job');
$add->addChild('designation','Manager');

$add=$main1->address->addChild('parent_name');
$add->addChild('father','Rony Jack');
$add->addChild('mother','Liena');

echo $main1->asXML(); 
?>
The output is here
<?xml version="1.0" standalone="true"?>
-<details> 
<name>Abcd</name> 
-<address> 
<door_no>234-ac</door_no> 
<street>Great Wall</street> 
<city>Alabama</city> 
	-<parent_name>
		<father>Rony Jack</father>
		<mother>Liena</mother>
	</parent_name>
</address> 
-<Job>
<designation>Manager</designation></Job>
</details>

Example using xml-sample2.xml

header('Content-Type: text/xml');

$str_xml = simplexml_load_file("xml-sample2.xml");
$main1 = new SimpleXMLElement($str_xml->asXML());
$add=$main1->addChild('Job');
$add->addChild('designation','Manager');

$add=$main1->address->addChild('parent_name');
$add->addChild('father','Rony Jack');
$add->addChild('mother','Liena');

$add=$main1->addChild('class','Four');
$add=$main1->addChild('Mark',70);

echo $main1->asXML();
Ouptut is here
<details>
<name>Abcd</name>
<address>
<door_no>234-ac</door_no>
<street>Great Wall</street>
<city>Alabama</city>
<parent_name>
<father>Rony Jack</father>
<mother>Liena</mother>
</parent_name>
</address>
<Job>
<designation>Manager</designation>
</Job>
<class>Four</class>
<Mark>70</Mark>
</details>

XML XML Children

Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer