簡體   English   中英

使用 DOMDocument/PHP/XML 的 appendChild

[英]appendChild using DOMDocument/PHP/XML

我正在嘗試根據 PHP 處理的 HTML 表單更新我的 XML 文件,但是我嘗試附加到當前 XML 的特定區域的新 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>

這是獲取根元素:

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

因此,您將一個子項附加到根目錄上,這就是為什么您總是看到它添加到文檔末尾附近的原因。 您需要像這樣獲取根元素的子元素:

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

這可以返回多種類型的 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

如果您可以傳遞所需節點的名稱而不是順序位置,或者更改 XML 以便子元素都具有相同的名稱並使用屬性來區分它們,則可以使用getElementsByTagName()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM