2013-05-21 49 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,以便子元素都具有相同的名称并使用属性来区分它们。