使用 php 问题更新 XML,包括 getElementsByTagName 并识别正确的子节点


update XML using php issues with getElementsByTagName and identifying the correct childnode

如何根据用户提交的表单中的 $_POST 变量识别正确的 XML 节点。 下面是我当前的 XML,其中包含一个注释,说明我是否希望放置新的 XML 数据,以及采用表单数据并准备将其插入到 XML 文档中的 PHP。

.XML:

<?xml version="1.0" encoding="UTF-8"?>
    <content_sets>

<!-- The new article node will be placed inside of one of the content_sets child nodes. Either doc_types, video_types, image_types. -->
    <doc_types>
        <article>
            <doc_name>Test Proposal</doc_name>
            <file_name>tes_prop.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>

提交时的 PHP:

$file_type = $_POST['file_type'];
//This is where the node name comes from
$doc = new DOMDocument();
$doc->load( 'rfp_files.xml' );
$doc->formatOutput = true;
$r = $doc->getElementsByTagName("content_sets")->getElementsByTagName($file_type);
*****//The above code is where my issue is coming from. I am not identifying the child node of content_sets correctly. 
$b = $doc->createElement("article");
$titleName = $doc->createElement("doc_name");
$titleName->appendChild(
    $doc->createTextNode( $Document_Array["name"] )
);
$b->appendChild( $titleName );

$r->appendChild( $b );
$doc->save("rfp_files.xml");

我没有显示窗体或其余article's子节点。如果需要,我可以发布更多我的代码。

使用

getElementsByTagName() 时,您需要使用 item() 方法,以便您可以在节点列表中检索特定节点 - 即使节点列表中只有一个项目,您仍然必须这样做。

getElementsByTagName()将始终返回一个 DOM 节点列表,因此您要么必须遍历列表,要么必须通过 item() 方法检索特定项目 - 这有意义吗?这里有一个例子:http://php.net/manual/en/domnodelist.item.php