2013-12-17 191 views
0

比方說,我已經是我加載一個像這樣的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() 

回答

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對象,而不是你設置的變量。

+0

然後我得到:'未定義的屬性:的DOMNodeList :: $ documentElement' – Michael

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