5

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>
Sonnet
  • 79
  • 1
  • 2
  • 7
  • Into which concrete problem are you running? Where is your code where you run into the error? What specifically does not work? Where do you hit the rock? Any error messages? Which of the existing solutions here on this website did not work for you? – M8R-1jmw5r Apr 30 '13 at 02:53

1 Answers1

3

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

michi
  • 6,565
  • 4
  • 33
  • 56
  • 1
    @sonnet: edit your question and include your PHP! It's easier to point you in the right direction then! – michi Apr 28 '13 at 20:38
  • I've created a new php with your code only changed the line $xml = simplexml_load_file('my_xml_file.xml'); but it is not workng. – Sonnet Apr 28 '13 at 21:19