How to delete an element from an XML tree where attribute is specific string in Simple XML PHP

Deadly 提交于 2019-12-08 04:58:54

问题


So I want to delete a child from an XML string where an attribute is a specific value.

For Example:

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

So how would I delete the note node with attribute http://yahoo.com as the string for the URL?

I'm trying to do this in PHP Simple XML

Oh and also I'm loading it in as an XML Object with the SimpleXML_Load_String function like this:

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

回答1:


SimpleXML does not have the remove child node feature,
there are cases you are can do How to deleted an element inside XML string?
but is depend on XML structure

Solution in DOMDocument

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



回答2:


It is possible to remove nodes with SimpleXML by using unset(), though there is some trickery to it.

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

If there are multiple matching nodes that you wish to delete, you could loop over them.

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


来源:https://stackoverflow.com/questions/7327106/how-to-delete-an-element-from-an-xml-tree-where-attribute-is-specific-string-in

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!