Search code examples
phpsimplexml

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?


Solution

  • 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();