问题
how do I identify the correct XML node based off a $_POST variable from a user submitted form. Below is my current XML with a note on were I want the new XML data to be placed and the PHP that takes the form data and prepares it to be inserted into the XML document.
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 on submit:
$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");
I did not show the form or the rest of article's
child nodes. If needed I can post more of my code.
回答1:
When using getElementsByTagName()
, you need to use the item()
method so you can retrieve a specific node in the node list - even if there is only one item in the node list, you still have to do this.
getElementsByTagName()
will always return a DOM Node List, so you either have to loop through the list, or you have to retrieve a specific item via the item() method - does that make sense? There is an example here: http://php.net/manual/en/domnodelist.item.php
来源:https://stackoverflow.com/questions/14555572/update-xml-using-php-issues-with-getelementsbytagname-and-identifying-the-correc