PHP domDocument按属性值删除元素

时间:2017-08-29 03:27:57

标签: php xml domdocument

我想删除某个变量声明的属性值的元素。我有一个像这样的xml:

<configuration name="acl.conf" description="Network Lists">
  <network-lists><!-- IMS ALLOW ONLY -->
    <list name="test" default="deny">
      <node type="allow" cidr="11.11.11.101/32"/>
   </list>
   <list name="customer" default="deny" type="allow">
      <node type="allow" cidr="10.13.13.193/32"/>
      <node type="allow" cidr="10.13.13.194/32"/>
      <node type="allow" cidr="10.13.13.3/32"/>
      <node type="allow" cidr="10.13.13.2/32"/>
   </list>
  </network-lists>
</configuration>

任何人都可以帮助我使用PHP代码吗?我试过这样的东西,但它不起作用。

    <?php
$doc = new DOMDocument; 
$id = $_GET['id'];
$doc->load('acl.conf.xml');

$searchNode = $doc->getElementsByTagName( "node" );

foreach( $searchNode as $searchNode )
{
    $valueID = $searchNode->getAttribute('cidr');

    } 
?>

1 个答案:

答案 0 :(得分:0)

假设$_GET['id']是您要删除的cidr值,我会使用XPath

$xpath = new DOMXPath($doc);
$nodes = $xpath->query('//node[@cidr="' . $id . '"]')
foreach ($nodes as $node) {
    $node->parentNode->removeChild($node);
}