2010-07-29 6 views
2

xml [php dom]을 사용하여 특정 요소가 있으면 반복해서 검사하지 마십시오. 예를 들어, 'activity'요소가있는 경우이 요소가 존재하면 xml 파일을 검사하고 그렇지 않으면 다시 작성하지 않습니다.xml 요소가 존재하면 종료하거나 건너 뜁니다.

다른 말로하면 'activity'요소를 처음에 한 번만 만들고 싶지만 다른 요소는 반복 될 수 있습니다.

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


?> 
+2

당신은 스크립트의 끝에서 그 "위치"헤더를 넣어해야합니다

은 PHP 코드입니다. – enobrev

+0

수정 해 주셔서 감사합니다. – input

답변

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