如果xml元素存在,则退出或跳过

时间:2010-07-29 17:15:53

标签: php xml domdocument

如何检查xml [with php dom]如果存在特定元素,则不应重复它。例如,如果我有一个元素'activity',它应该检查xml文件是否存在该元素,如果存在,它将不再创建它。

换句话说,我想在开头只创建一次元素'activity',但其他元素可以重复出现。

这是php代码:

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


?>

1 个答案:

答案 0 :(得分:14)

if ($xmldoc->getElementsByTagName("activity")->length == 0) {
    $newElement = $xmldoc->createElement('activity'); 
    $root->appendChild($newElement);
}