使用item()将数据插入XML文档


Using item() to insert data into XML document

我试图将数据插入我的XML文档到content_set的特定节点,我认为我必须使用item(),但每次我提交我的表单,数据被放在我的文档的末尾,但在结束前content_sets

PHP:

//这是我认为我会选择什么节点的数据是基于在我的html中选择的值,0是doc_types和1是video_types

$file_type = $_POST['file_type'];
$doc = new DOMDocument();
$doc->load( 'myfile_files.xml' );
$doc->formatOutput = true;
$r = $doc->getElementsByTagname('content_sets')->item($file_type);
$b = $doc->createElement("article");
$titleName = $doc->createElement("doc_name");
$titleName->appendChild(
$doc->createTextNode( $Document_Array["name"] )
);
$b->appendChild( $titleName );

$r->appendChild( $b );
$doc->save("myfile_files.xml");
XML:

<?xml version="1.0" encoding="UTF-8"?>
<content_sets>
    <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>
</content_sets>
HTML:

 <p>Content Type:<br/>
<select name="file_type">
    <option value="0">Document</option>
    <option value="1">Video</option>
    <option value="2">Image</option>
</select></p>

我试图包括脚本的最重要的部分,但如果需要,可以张贴所有的。

谢谢!

1)使用XPath查找要更改的节点

2)一旦你有了节点,只需给它分配一个新值。

3)完成后写入文件

查看这些链接了解更多详情:

  • 在PHP中修改XML节点元素值并保存文件

  • http://quest4knowledge.wordpress.com/2010/09/04/php-xml-create-add-edit-modify-using-dom-simplexml-xpath/
  • http://www.ibm.com/developerworks/opensource/library/x-xpathphp/?ca=drs-