I have some XML to which I need to add a child.
Using SimpleXML, I'm not having any issue adding a simple node.
The beginning XML looks a bit like this:
<root>
<item>
<title>This is the title</title>
<sort>2</sort>
</item>
<item>
<title>This is another title</title>
<sort>3</sort>
</item>
</root>
I need to add a node that looks like this:
<label id=1>
<title type=normal>This is a label</title>
<sort>1</sort>
</label>
The result would be:
<root>
<item>
<title>This is the title</title>
<sort>2</sort>
</item>
<item>
<title>This is another title</title>
<sort>3</sort>
</item>
<label id=1>
<title type=normal>This is a label</title>
<sort>1</sort>
</label>
</root>
I'm able to add a simple child using:
$xml->root->addChild('label', 'This is a label');
I am having trouble getting the attributes and children added to this newly added node though.
I am not worried about appending versus prepending as the sorting happens in XSLT.
addChild returns the added child, so you just have to do :
$label = $xml->root->addChild('label');
$label->addAttribute('id', 1);
$title = $label->addChild('title', 'This is a label');
$title->addAttribute('type', 'normal');
$label->addChild('sort', 1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With