[英]Keeping line breaks when using PHP's DomDocument 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.