Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add node in existing xml using php simpleXML?

I have a xml file like the bellow, and I need to add a new node with some child node and attribute.

<custscales>
    <custscale sclNo="1" type="lin">
        <scaleName>Custom Scale Lin</scaleName>
        <jsfunc>custLin</jsfunc>
    </custscale>
    <custscale sclNo="2" type="map">
        <scaleName>Custome Scale Map</scaleName>
        <jsfunc>custMap</jsfunc>
    </custscale>
    <custscale sclNo="3" type="pol">
        <scaleName>Custome Scale Pol</scaleName>
        <jsfunc>custPol</jsfunc>
    </custscale>
    <custscale sclNo="4" type="tbl1">
        <scaleName>Custome Scale Table</scaleName>
        <jsfunc>custTbl1</jsfunc>
    </custscale>
</custscales>

Now I want a new custscale node as bellow in my existing xml file:

<custscale sclNo="5" type="tbl1">
    <scaleName>Custome Scale New</scaleName>
    <jsfunc>custTbl1</jsfunc>
</custscale>
like image 395
Sonnet Avatar asked Oct 22 '22 11:10

Sonnet


1 Answers

Use addChild() and addAttribute():

$xml = simplexml_load_string($x); // assume XML in $x

$cs = $xml->addChild('custscale','');
$cs->addAttribute('sclNo','5');
$cs->addChild('scaleName','Some Name');
// add other attributes and child-nodes

see it working: http://codepad.viper-7.com/Y13JbS

like image 148
michi Avatar answered Oct 24 '22 03:10

michi