问题描述
我正在尝试构建一个相当复杂的XML文档.
I'm trying to build a rather complex XML document.
我有一堆重复的XML文档.我以为我会使用多个字符串模板作为这些部分的基础文档,并使用simplexml_load_string创建XML元素的实例.
I have a bunch of sections of the XML document that repeats. I thought I'd use multiple string templates as base document for the sections and create instances of XML elements using simplexml_load_string.
所以我有一个SimpleXMLElement实例作为基础文档
So I have one instance of SimpleXMLElement as the base document
然后我遍历数据库中的某些项目,创建新的SimpleXMLElement,如下所示:
then I loop through some items in my database, create new SimpleXMLElement, something like this:
$ item = simplexml_load_string($ template_item); //处理项目 //尝试将项目添加到根文档中. //卡在这里..不能做$ root-> items-> addChild($ item)
$item = simplexml_load_string($template_item); // do stuff with item // try to add item to the root document..
// Stuck here.. can't do $root->items->addChild($item)
endfor;
我无法调用addChild,因为它只需要标记名称和值.您不能将另一个SimpleXMLElement添加到addChild中.
I can't call addChild because it just expects a tag name and value.. you can't addChild another SimpleXMLElement.
我在这里错过了什么吗? addChild不能将SimpleXMLELement作为参数似乎很愚蠢.
Am I missing something here? seems really dumb that addChild can't take a SimpleXMLELement as a parameter.
还有其他方法可以做到吗? (除了使用其他xml库之外)
Is there any other way to do this? (apart from using a different xml lib)
推荐答案
据我所知,您无法使用SimpleXML,因为addChild
不会对元素进行深层复制(必须指定可以通过调用SimpleXMLElement::getName()
轻松克服标签名称.
As far as I know, you can't do it with SimpleXML because addChild
doesn't make a deep copy of the element (being necessary to specify the tag name can easily be overcome by calling SimpleXMLElement::getName()
).
一种解决方案是改为使用DOM:
One solution would be to use DOM instead:
具有此功能:
function sxml_append(SimpleXMLElement $to, SimpleXMLElement $from) {
$toDom = dom_import_simplexml($to);
$fromDom = dom_import_simplexml($from);
$toDom->appendChild($toDom->ownerDocument->importNode($fromDom, true));
}
我们有
<?php
header("Content-type: text/plain");
$sxml = simplexml_load_string("<root></root>");
$n1 = simplexml_load_string("<child>one</child>");
$n2 = simplexml_load_string("<child><k>two</k></child>");
sxml_append($sxml, $n1);
sxml_append($sxml, $n2);
echo $sxml->asXML();
输出
<?xml version="1.0"?>
<root><child>one</child><child><k>two</k></child></root>
另请参阅一些使用递归函数和addChild
的用户注释,例如这一个.
See also some user comments that use recursive functions and addChild
, e.g. this one.
这篇关于PHP-SimpleXML-AddChild与另一个SimpleXMLElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!