How to add node in existing xml using php simpleXML?

Sonnet picture Sonnet · Apr 28, 2013 · Viewed 11.1k times · Source

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>

Answer

michi picture michi · Apr 28, 2013

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