删除php

时间:2018-01-16 19:02:54

标签: php xml

我想从my xml中删除所有带有category = phones的产品:

<SHOP>
  <ITEM>
    <CATEGORY>Computers</CATEGORY>
    <NAME>DELL</NAME>
  </ITEM>
  <ITEM>
    <CATEGORY>Computers</CATEGORY>
    <NAME>IBM</NAME>
  </ITEM>
  <ITEM>
    <CATEGORY>Phones</CATEGORY>
    <NAME>Apple</NAME>
  </ITEM>
</SHOP>

我试过这个解决方案:

$doc = new DomDocument();
$doc->load('product.xml');
$xpath = new DomXPath($doc);
$nodes = $xpath->query('ITEM/CATEGORY');

for ($i = 0; $i < $nodes->length; $i++) {     
    $node = $nodes->item($i);       
    if ($node->nodeValue == 'Phones') {
        $node->parentNode->removeChild($node);
    }         
}

但是它只删除属性CATEGORY但我需要删除所有具有thit类别的ITEM节点。我该如何更改代码?

1 个答案:

答案 0 :(得分:1)

您要从项目中删除类别。您想要从商店中删除商品(父母双方)。最简单的方法:

$node->parentNode->parentNode->removeChild($node->parentNode);

在行动at 3v4l here中查看:

<?php

$xml_string = <<<EOT
<SHOP>
  <ITEM>
    <CATEGORY>Computers</CATEGORY>
    <NAME>DELL</NAME>
  </ITEM>
  <ITEM>
    <CATEGORY>Computers</CATEGORY>
    <NAME>IBM</NAME>
  </ITEM>
  <ITEM>
    <CATEGORY>Phones</CATEGORY>
    <NAME>Apple</NAME>
  </ITEM>
</SHOP>
EOT;

$doc = new DomDocument();
$doc->loadXML($xml_string);
$xpath = new DomXPath($doc);
$nodes = $xpath->query('ITEM/CATEGORY');

for ($i = 0; $i < $nodes->length; $i++) {     
    $node = $nodes->item($i);
    if ($node->nodeValue == 'Phones') {
        $node->parentNode->parentNode->removeChild($node->parentNode);
    }         
}

echo $doc->saveXML();