views:

37

answers:

1

how do i check in xml [with php dom] that if a particular element exists, it should not repeat it. for example, if i have an element 'activity', it should check against the xml file if this element exists, and if it does, it will not create it again.

in other words, i would like to create the element 'activity' only once in the beginning, but the other elements can be recurring.

this is the php code:

<?php
    header("Location: index.php");

    $xmldoc = new DOMDocument();
    if(file_exists('sample.xml')){
    $xmldoc->load('sample.xml');
    } else {
    $xmldoc->loadXML('<root/>');
    }
    $newAct = $_POST['activity'];
    $newTime = $_POST['time'];

    $root = $xmldoc->firstChild;

    $newElement = $xmldoc->createElement('activity'); 
    $root->appendChild($newElement);

    $newText = $xmldoc->createTextNode($newAct);
    $newElement->appendChild($newText);

    $newElementE = $xmldoc->createElement('time');
    $root->appendChild($newElementE);

    $newTextE = $xmldoc->createTextNode($newTime);
    $newElementE->appendChild($newTextE);

    $xml->formatOutput = true; 
    $xmldoc->save('sample.xml');


?>
+3  A: 
if ($xmldoc->getElementsByTagName("activity")->length == 0) {
    $newElement = $xmldoc->createElement('activity'); 
    $root->appendChild($newElement);
}
Artefacto