简体   繁体   中英

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM