2011-04-19 112 views
3

我有一些XML我需要添加一個孩子。SimpleXML添加孩子和屬性

使用SimpleXML,我沒有任何問題添加一個簡單的節點。

的開始XML看起來有點像這樣:

<root> 
    <item> 
     <title>This is the title</title> 
     <sort>2</sort> 
    </item> 
    <item> 
     <title>This is another title</title> 
     <sort>3</sort> 
    </item> 
</root> 

我需要補充的是這樣的一個節點:

<label id=1> 
     <title type=normal>This is a label</title> 
     <sort>1</sort> 
    </label> 

其結果將是:

<root> 
    <item> 
     <title>This is the title</title> 
     <sort>2</sort> 
    </item> 
    <item> 
     <title>This is another title</title> 
     <sort>3</sort> 
    </item> 
    <label id=1> 
     <title type=normal>This is a label</title> 
     <sort>1</sort> 
    </label> 
</root> 

我可以添加一個簡單的孩子使用:

$xml->root->addChild('label', 'This is a label'); 

雖然我無法獲取屬性和子添加到這個新添加的節點。

我不擔心在XSLT中進行排序時追加與預先計劃相關。

+2

你想要做什麼說明書中加以說明。 http://docs.php.net/manual/en/simplexml.examples-basic.php(示例#10) – 2011-04-19 16:33:24

回答

11

的addChild返回添加的孩子,所以你只需要做:

$label = $xml->root->addChild('label'); 
$label->addAttribute('id', 1); 
$title = $label->addChild('title', 'This is a label'); 
$title->addAttribute('type', 'normal'); 
$label->addChild('sort', 1); 
+0

感謝切割/粘貼能力 - 時間緊迫。這正是我所期待的。 – ropadope 2011-04-19 14:53:06

1
$xml->root->addChild('label', 'This is a label'); 

此操作返回剛剛添加的孩子的引用。所以,你可以這樣做:

$child = $xml->root->addChild('label', 'This is a label'); 

這個,你不能加入你額外的兒童和屬性那個孩子。

$child->addAttributes('id', '1'); 

由於它返回一個引用,只是補充說,節點和屬性是$ XML對象的一部分。

+0

它是如何工作的很好的解釋。 – ropadope 2011-04-19 14:52:37