2013-05-21 101 views
0

我想基於PHP處理的HTML表單來更新我的XML文件,但是我試圖追加到我當前XML的特定區域的新XML片段只是不斷被添加到結尾我的文件。appendChild使用DomDocument/PHP/XML

$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實例:

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

這是獲得根元素:

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

所以要附加一個孩子到這就是爲什麼你總是看到它添加的根靠近文檔的末尾。您需要獲得根元素的孩子是這樣的:

$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,以便子元素都具有相同的名稱並使用屬性來區分它們。