简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM