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

Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com











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