0

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

1 に答える 1

1

これはルート要素を取得しています:

$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

順序位置の代わりに必要なノードの名前を渡すことができるgetElementsByTagName()場合、または子要素がすべて同じ名前を持つように XML を変更し、属性を使用してそれらを区別できる場合に使用できます。

于 2013-05-21T21:37:22.797 に答える