Question

Hello!

i have a problem, Im trying to remove Element (With childs) according to one Child value: Here is the XML Sample:

    <?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>

Now i need to remove All of the specific "CHILD" element (Incl. children) that its "endtime" value is older then now (Or simply "endtime" is equal to specific value)

"endtime" is a date with the format: yyyymmddHHMMSS

Here is my first try (without success) :

    $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(); 

Thank you Very Much!

Was it helpful?

Solution 2

Hi again!

After a full day of research.. finally i have found the problem..

First thank you Michael for your help.

Here is the final and working code:

<?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)
?>

i havn't found it anywhere, so I hope this will help you.. :)

OTHER TIPS

Use XPath to query for document nodes. Try this:

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

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

$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);
}

Here's a nice page with XPath examples.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top