将子项添加到特定节点

时间:2013-12-17 03:31:03

标签: php xml dom

假设我已经有一个XML文件,我加载如下:

$domtree = new DOMDocument('1.0', 'UTF-8');
$domtree->load('test.xml');

XML文件的结构如下:

<software>
    <info>
        <version>6.3</version>
    </info>
    <some_stuff>
        <test1>
            <somedata>adsd</somedata>
        </test1>
    </some_stuff>
</software>

如何在解密中添加新元素?

我试过了:

$some_stuff = $domtree->getElementsByTagName('software');
$some_stuff = $some_stuff->getElementsByTagName('some_stuff');
$funcgroup = $some_stuff->appendChild($domtree->createElement('test2'));

PHP错误:

Call to undefined method DOMNodeList::getElementsByTagName()

2 个答案:

答案 0 :(得分:1)

此代码可以使用

$domtree  = new \DomDocument("1.0","UTF-8");
            $xmlfile    = "test.xml";
            $domtree->load($xmlfile);
            $xml_stuff          = $domtree->getElementsByTagName('some_stuff')-> item(0) ;
            $xmlNode1           = $domtree->createElement('test2');
            $xmlNode1           = $xml_stuff->appendChild($xmlNode1);
            $domtree->preserveWhiteSpace = false;
            $domtree->FormatOutput=true;
            $domtree->saveXML();
            $domtree->save($xmlfile);

答案 1 :(得分:0)

编辑:我的错误解决方案......

$domtree是你的对象。您无法将$some_stuff设置为其值并将其用作对象。这就是你得到未定义方法错误的原因。

这段代码可以使用(虽然它没有达到你想要的效果):

$domtree->loadXML(file_get_contents('test.xml'));
$some_stuff = $domtree->getElementsByTagName('software');
$some_stuff = $domtree->getElementsByTagName('some_stuff');
$funcgroup = $domtree->appendChild($domtree->createElement('test2'));

请注意我是如何引用每行中的$domtree对象而不是您正在设置的变量。