我有两个xml数组,我想在第三个数组中合并这些数组......第一个xml结构是
$current = '<forms id="frm16648">
<group ref="" id="tarascioheader" mode="block">
<label>
<![CDATA[Group (tarascioheader)]]>
</label> structure u
<select ref="" id="petorresp">
<label>
<![CDATA[Select (petorresp)]]>
</label>
</select>
,第二个数组是
$old = '<forms id="frm16648">
<group ref="" id="tarascioheader" mode="block">
<label>
<![CDATA[abc]]>
</label>
</group>
</forms>':
</group>
</forms>';
从这些xmls中,我想复制新数组中的所有匹配标签.... 我试图通过递归函数来做到这一点....
function merge_xmls($current, $old)
{
$cxml = str_get_html($current);
$oxml = str_get_html($old);
do
{
$tt = $cxml->first_child();
if(!empty($tt) && !is_null($cxml->first_child()))
{
$x = $cxml->first_child();
$this->merge_xmls($x, $cxml, $oxml);
}
if(empty($tt))
{
$cid = $cxml->id;
$oid = $oxml -> find('#'.$cid);
if(!is_null($oid))
{
$cxml -> innerHTML = $oxml -> innerHTML;
}
}
$cxml = $cxml->next_sibling();
}
while(!empty($cxml) && !is_null($cxml));
}
答案 0 :(得分:0)
从您发布的伪代码看起来,您希望将一个xml元素的子代复制到另一个。当我使用不同的解析器时,我对它有点不同,但是相同:
我在这里使用DOMDocument,因为它非常适合像这样的专用操作:
$doc = new DOMDocument();
$copyTo = $doc->createDocumentFragment();
$copyTo->appendXML($current);
$copyFrom = new DOMDocument();
$copyFrom->loadXML($old);
$xpath = new DOMXPath($copyFrom);
foreach (new DOMElementFilter($copyTo->childNodes, 'forms') as $form) {
$id = $form->getAttribute('id');
$expression = sprintf('(//*[@id=%s])[1]', xpath_string($id));
$copy = $xpath->query($expression)->item(0);
if (!$copy) {
throw new UnexpectedValueException("No element with ID to copy from \"$id\"");
}
dom_replace_children($copy, $form);
}
输出为:
echo $doc->saveXML($doc->importNode($copyTo, TRUE));
并给出:
<forms id="frm16648">
<group ref="" id="tarascioheader" mode="block">
<label>
<![CDATA[abc]]>
</label>
</group>
</forms>
这里的帮助程序是:
function dom_remove_children(DOMElement $node)
{
while ($node->firstChild) {
$node->removeChild($node->firstChild);
}
}
function dom_replace_children(DOMElement $from, DOMElement $into)
{
dom_remove_children($into);
$doc = $into->ownerDocument;
foreach ($from->childNodes as $child) {
$into->appendChild($doc->importNode($child, TRUE));
}
}
同样DOMElementFilter
class(通过PHP DOM: How to get child elements by tag name in an elegant manner?),还有xpath_string()
function (也称为shown on Stackoverflow)。
希望这有帮助,该示例以这种方式为您处理数据:https://eval.in/59886