如何使用php simpleXML在现有的xml中添加节点?

时间:2013-04-28 19:08:20

标签: php xml simplexml addattribute

我有一个像bellow一样的xml文件,我需要添加一个带有一些子节点和属性的新节点。

<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>

现在我想在我现有的xml文件中显示一个新的custscale节点:

<custscale sclNo="5" type="tbl1">
    <scaleName>Custome Scale New</scaleName>
    <jsfunc>custTbl1</jsfunc>
</custscale>

1 个答案:

答案 0 :(得分:2)

使用addChild()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

看到它有效:http://codepad.viper-7.com/Y13JbS