PHP XML:根据节点值删除Element和所有子节点?

时间:2012-07-27 10:47:16

标签: php dom removechild

您好!

我有一个问题,我试图根据一个Child值删除Element(With childs): 这是XML示例:

    <?xml version="1.0" encoding="UTF-8"?>
    <Businesses>
    <Business NAME="busin1">
    <CHILD ID="30"><title>child Title</title>
    <description>Child Description</description>
    <urlToSite>http://www.MySite.co.il</urlToSite>
    <endtime>20120720103000</endtime>
    <starttime>20120710191500</starttime>
    </CHILD> 
<CHILD>...</CHILD>
<CHILD>...</CHILD>
</Business>
    </Businesses>

现在我需要删除所有特定的“CHILD”元素(包括孩子),它的“endtime”值现在比现在更长(或者只是“endtime”等于特定值)

“endtime”是格式为的日期:yyyymmddHHMMSS

这是我的第一次尝试(没有成功):

    $doc = new DOMDocument; 
    $doc->load('MyXML.xml'); //The XML Above

    $thedocument = $doc->documentElement;

    //this gives you a list of the childs
    $list = $thedocument->getElementsByTagName('CHILD');

    //figure out which ones you want -- assign it to a variable (ie: $nodeToRemove )
    $nodeToRemove = null;
$time=date("YmdHis",time ());
    foreach ($list as $domElement){
 $attrValue = $domElement->childNodes->item('endtime')->nodeValue; //not Sure about this!!
      if ($attrValue > $time) {
        $nodeToRemove = $domElement;
      }
    }

    //Now remove it.
    if ($nodeToRemove != null)
    $thedocument->removeChild($nodeToRemove);
    echo $doc->saveXML(); 

非常感谢!

1 个答案:

答案 0 :(得分:1)

再次嗨!

经过一整天的研究......终于我找到了问题..

首先感谢Michael的帮助。

这是最终的和有效的代码:

<?php

$doc = new DOMDocument; 
$doc->load('MyXML.xml');

$maxTime = date("YmdHis", time());

$xpath = new DOMXPath($doc);
$q = "/Businesses/Bisiness/CHILD/endtime[. < {$maxTime}]";
foreach ($xpath->query($q) as $node) {
    $businessNode = $node->parentNode;
    $businessesNode = $businessNode->parentNode;
    $businessesNode->removeChild($businessNode);
}

// inserting to variable ONLY
$last = $doc->saveXml();
// IMPORTANT!! - we have to rewrite to XML the Results back!!
file_put_contents('MyXML.xml', $last)
?>

我没有在任何地方找到它,所以我希望这会对你有所帮助.. :)