Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleXML adding child with children and attributes

Tags:

php

xml

simplexml

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.

like image 676
ropadope Avatar asked Dec 04 '22 08:12

ropadope


1 Answers

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);
like image 178
yent Avatar answered Dec 16 '22 08:12

yent