0

I'm trying to add a child to an Simple XML object, but when an element with the same name already exists on that level it doesn't get added.

Here's what I'm trying:

$str = '<?xml version="1.0"?>
    <root>
        <items>
            <item></item>
        </items>
    </root>';

$xml = new SimpleXMLElement($str);
$xml->addChild('items');
print $xml->asXML();

I get the exact same xml as I started with, when what I really want is a second empty items element. If I use another element name than it does get added.

4

2 に答える 2

1

このコードを使用して、例に新しいアイテム ノードを追加します。

$str = '<?xml version="1.0"?>
<root>
    <items>
        <item></item>
    </items>
</root>';

$xml = new SimpleXMLElement($str);
$xml->addChild('items', '');
var_dump($xml->asXML());

どの出力:

string '<?xml version="1.0"?>
<root>
    <items>
        <item/>
    </items>
<items></items></root>
' (length=109)
于 2012-06-28T11:54:13.743 に答える
0

simpleloadxml代替として使用できます

$xml = simplexml_load_file("myxml.xml");
$sxe = new SimpleXMLElement($xml->asXML());
$itemsNode = $sxe->items[0];
$itemsNode->addChild("item", $newValue);
$sxe->asXML("myxml.xml"); 
于 2012-06-28T12:02:07.567 に答える