如何根据子条件PHP删除XML父节点

时间:2015-08-04 08:11:13

标签: php xml dom xpath

您好我正在尝试从我不需要的位置清理xml文件。到目前为止,这是我的代码:

<?php
    $doc = new DOMDocument;
    $doc->load('merg.xml');

    $xpath = new DOMXPath($doc);

    $products = $xpath->query('//offer/products/*');

    printf('There is %d products<br /><br />', $products->length);

    function findStopPointByName($xml, $query) {
      $upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZĄŻŚĆŹĆÓŁ";
      $lower = "abcdefghijklmnopqrstuvwxyzążśćźńół";
      $arg_query    = "translate('$query', '$upper', '$lower')";

      return $xml->query("//offer/products/product/description/name[contains(text(),$arg_query)]");
    }
    foreach(findStopPointByName($xpath,'Skór') as $node)
    {
        $node->parentNode->removeChild($node);
    }

    $doc->save('merg_fixed.xml');
?>

XML的结构:

<offer>
 <products>
  <product>
   <description>
    <name>Name of the product</name>
     ...
    </name>
     ...
   </description>
  </product>
 </products>
</offer>

我试图在任何情况下删除其名称中包含'Skór'的所有PRODUCT(Skór,skór,SKÓR - 足够)。 Funcion findStopPointByName返回正确长度的DOMNodeList,但没有从实际XML文件中删除任何内容,请帮忙。

1 个答案:

答案 0 :(得分:1)

首先,您可以直接找到条件为

的节点产品

其次,为了使搜索不区分大小写,您可以在任何情况下转换节点文本,但应该在相同的情况下使用模式。结果,您的代码可能如此

 function findStopPointByName($xml, $query) {
  $upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZĄŻŚĆŹĆÓŁ";
  $lower = "abcdefghijklmnopqrstuvwxyzążśćźńół";
  $arg_query    = "translate(text(), '$upper', '$lower')";
  $q = "//product[description/name[contains($arg_query, '$query')]]" ."\n";
  return $xml->query($q);
}

$doc = new DOMDocument;
$doc->load('merg.xml');
$xpath = new DOMXPath($doc);
foreach(findStopPointByName($xpath,'skór') as $node)
    $node->parentNode->removeChild($node);

echo $doc->saveXML();

Demo on eval.in