Remove a child with a specific attribute, in SimpleXML for PHP

后端 未结 17 2365
星月不相逢
星月不相逢 2020-11-22 02:50

I have several identical elements with different attributes that I\'m accessing with SimpleXML:


    
    

        
17条回答
  •  清酒与你
    2020-11-22 02:58

    Even though SimpleXML doesn't have a detailed way to remove elements, you can remove elements from SimpleXML by using PHP's unset(). The key to doing this is managing to target the desired element. At least one way to do the targeting is using the order of the elements. First find out the order number of the element you want to remove (for example with a loop), then remove the element:

    $target = false;
    $i = 0;
    foreach ($xml->seg as $s) {
      if ($s['id']=='A12') { $target = $i; break; }
      $i++;
    }
    if ($target !== false) {
      unset($xml->seg[$target]);
    }
    

    You can even remove multiple elements with this, by storing the order number of target items in an array. Just remember to do the removal in a reverse order (array_reverse($targets)), because removing an item naturally reduces the order number of the items that come after it.

    Admittedly, it's a bit of a hackaround, but it seems to work fine.

提交回复
热议问题