2011-09-06 44 views
1

所以我想從屬性是特定值的XML字符串中刪除子元素。如何從XML樹中刪除元素,其中屬性是簡單XML中的特定字符串PHP

例如:

<xml> 
    <note url="http://google.com"> 
    Values 
    </note> 
    <note url="http://yahoo.com"> 
    Yahoo Values 
    </note> 
</xml> 

那麼我將如何刪除與屬性http://yahoo.com作爲字符串的URL的說明節點?

我試圖做到這一點在PHP中簡單的XML

哦,也是我在加載它作爲與SimpleXML_Load_String功能像這樣的XML對象:

$notesXML = simplexml_load_string($noteString['Notes']); 
+0

類似的問題:http://stackoverflow.com/questions/262351/remove-a-child-with-a-specific-attribute-in-simplexml-for-php –

+0

你從哪裏弄來'$ noteString從? – krummens

回答

2

的SimpleXML沒有刪除子節點功能,
有這樣的情況,你是可以做How to deleted an element inside XML string?
而是依賴於XML結構

解決方案在DOM文檔

$doc = new DOMDocument; 
$doc->loadXML($noteString['Notes']); 

$xpath = new DOMXPath($doc); 
$items = $xpath->query('note[@url!="http://yahoo.com"]'); 

for ($i = 0; $i < $items->length; $i++) 
{ 
    $doc->documentElement->removeChild($items->item($i)); 
} 
+0

這工作,這個解決方案也可以工作:http://stackoverflow.com/questions/262351/remove-a-child-with-a-specific-attribute-in-simplexml-for-php – Talon

1

有可能通過使用unset()除去用SimpleXML節點,雖然有一些掛羊頭賣狗肉吧。

$yahooNotes = $notesXML->xpath('note[@url="http://yahoo.com"]'); 
// We know there is only one so access it directly 
$noteToRemove = $yahooNotes[0]; 
// Unset the node. Note: unset($noteToRemove) would only unset the variable 
unset($noteToRemove[0]); 

如果您想刪除多個匹配節點,可以循環它們。

foreach ($yahooNotes as $noteToRemove) { 
    unset($noteToRemove[0]); 
} 
+0

是的!非常感謝!這有助於太多......而這甚至不是我的問題! – krummens