2010-07-05 26 views
6

我遇到了simpleXml問題並添加了新項目。這是我的xml:使用使用PHP simpleXml將子項添加到xml中

<?xml version="1.0" encoding="utf-8"?> 
<root> 
    <items>    
    <item>abc</item> 
    <item>def</item> 
    <item>ghi</item> 
</items> 
</root> 

林這個PHP代碼:

$xml = simplexml_load_file("myxml.xml"); 
$sxe = new SimpleXMLElement($xml->asXML()); 
$newItem = $sxe->addChild("items"); 
$newItem->addChild("item", $newValue); 
$sxe->asXML("myxml.xml"); 

這是結果:

<?xml version="1.0" encoding="utf-8"?> 
    <root> 
     <items>    
     <item>abc</item> 
     <item>def</item> 
     <item>ghi</item> 
     </items> 
     <items> 
     <item>jkl</item> 
     </items> 
    </root> 

這造成了我新的項目節點,但我想補充項目相同的已有項目節點。

回答

9

那麼,你不應該創建新的項目節點:

$xml = simplexml_load_file("myxml.xml"); 
$sxe = new SimpleXMLElement($xml->asXML()); 
$itemsNode = $sxe->items[0]; 
$itemsNode->addChild("item", $newValue); 
$sxe->asXML("myxml.xml"); 
0

您是否嘗試過做以下方式

$newItem->root->items[0]->addChild("item","Test"); 

或者

$newItem->root->items->addChild("item","Test"); 
0

你可以使用這個類的SimpleXML接受孩子的物體追加

<?php 

    class MySimpleXMLElement extends SimpleXMLElement 
    { 
     /** 
     * Add SimpleXMLElement code into a SimpleXMLElement 
     * 
     * @param MySimpleXMLElement $append 
     */ 
     public function appendXML($append) 
     { 
      if ($append) { 
       if (strlen(trim((string)$append)) == 0) { 
        $xml = $this->addChild($append->getName()); 
       } else { 
        $xml = $this->addChild($append->getName(), (string)$append); 
       } 

       foreach ($append->children() as $child) { 
        $xml->appendXML($child); 
       } 

       foreach ($append->attributes() as $n => $v) { 
        $xml->addAttribute($n, $v); 
       } 
      } 
     } 
    }