Ken J
Ken J

Reputation: 4562

SimpleXMLElement Add Child Closure

I'm trying to create a simple XML document but I'm having difficulty grouping the children appropriately. My XML should look like this:

<news>
    <abc>
        <content>test</content>
    </abc>
    <abc>
        <content2>test2</content2>
    </abc>
</news>

I'm using the following code:

$newsXML = new SimpleXMLElement("<news></news>");
$news = $newsXML->addChild('abc');
$news->addChild('content','test');
$news->addChild('content2','test2');
echo $newsXML->asXML();

and getting this:

<news>
    <abc>
        <content>test</content>
        <content2>test2</content2>
    </abc>
</news>

How do I separate the children?

Upvotes: 1

Views: 100

Answers (1)

Musa
Musa

Reputation: 97672

Since you want 2 abc child tags, you have to create 2 not 1

$newsXML = new SimpleXMLElement("<news></news>");
$news1 = $newsXML->addChild('abc');
$news1->addChild('content','test');
$news2 = $newsXML->addChild('abc');
$news2->addChild('content2','test2');
echo $newsXML->asXML();

Upvotes: 1

Related Questions