2013-05-21 5 views
0

PHP로 처리 된 HTML 양식을 기반으로 XML 파일을 업데이트하려고하지만 현재 XML의 특정 영역에 추가하려고하는 새로운 XML 코드 조각이 계속 끝에 추가됩니다. 내 문서의.DomDocument/PHP/XML을 사용하는 appendChild

$specific_node = "0"; //this is normally set by a select input from the form. 
$doc = new DOMDocument(); 
$doc->load('rfp_files.xml'); 
$doc->formatOutput = true; 

//below is where my issue is having problems the variable '$specific_node' can be one of three options 0,1,2 and what I am trying to do is find the child of content_sets. So the first second or third child elemts and that is where I will add my new bit of XML 
$r = $doc->getElementsByTagname('content_sets')->item($specific_node); 

//This is where I build out my new XML to append 
$fileName = $doc->createElement("file_name"); 
$fileName->appendChild(
    $doc->createTextNode($Document_Array["url"]) 
); 
$b->appendChild($fileName); 

//this is were I add the new XML to the child node mention earlier in the script. 
$r->appendChild($b); 

XML 예 :

$specific_node = "0"; 
$r = $doc->getElementsByTagname('content_sets')->item($specific_node); 

그래서 당신은 당신이 항상 추가 참조 왜 루트에 아이를 추가하는이 루트 요소를 받고있다

<?xml version="1.0" encoding="UTF-8"?> 
<content_sets> 
    <doc_types> 
    <article> 
     <doc_name>Additional</doc_name> 
     <file_name>Additional.docx</file_name> 
     <doc_description>Test Word document. Please remove when live.</doc_description> 
     <doc_tags>word document,test,rfp template,template,rfp</doc_tags> 
     <last_update>01/26/2013 23:07</last_update> 
    </article> 
    </doc_types> 
    <video_types> 
    <article> 
     <doc_name>Test Video</doc_name> 
     <file_name>test_video.avi</file_name> 
     <doc_description>Test video. Please remove when live.</doc_description> 
     <doc_tags>test video,video, avi,xvid,svid avi</doc_tags> 
     <last_update>01/26/2013 23:07</last_update> 
    </article> 
    </video_types> 
    <image_types> 
    <article> 
    <doc_name>Test Image</doc_name> 
    <file_name>logo.png</file_name> 
    <doc_description>Logo transparent background. Please remove when live.</doc_description> 
    <doc_tags>png,logo,logo png,no background,graphic,hi res</doc_tags> 
    <last_update>01/26/2013 23:07</last_update> 
    </article> 
    </image_types> 
</content_sets> 

답변

1

문서의 끝 부분.

$children = $doc->documentElement->childNodes; 

이 여러 types of node 반환 할 수 있습니다,하지만 당신은 '요소'유형의 노드에만 관심이 :이 같은 루트 요소의 자식을 얻을 필요가있다.

$j = 0; 
foreach ($doc->documentElement->childNodes as $r) 
    if ($r->nodeType === XML_ELEMENT_NODE && $j++ == $specific_node) 
     break; 

if ($j <= $specific_node) 
    // handle situation where $specific_node is more than number of elements 

대신 요구되는 노드의 이름을 전달 할 수 있다면 당신은 getElementsByTagName()를 사용할 수 ... 아주 우아한 아니지만, 유일한 방법은 내가 위치하여 자식 요소는 다음과 같이 루핑 얻을 발견했습니다 서수 위치를 지정하거나 XML을 변경하여 하위 요소가 모두 동일한 이름을 가지며 특성을 사용하여 차별화 할 수 있습니다.