php xml 插入节点,PHP SimpleXML:在特定位置插入节点

小编典典

以下是在其他一些SimpleXMLElement之后插入新的SimpleXMLElement的函数。由于使用SimpleXML不可能直接做到这一点,因此它在幕后使用了一些DOM类/方法来完成工作。

function simplexml_insert_after(SimpleXMLElement $insert, SimpleXMLElement $target)

{

$target_dom = dom_import_simplexml($target);

$insert_dom = $target_dom->ownerDocument->importNode(dom_import_simplexml($insert), true);

if ($target_dom->nextSibling) {

return $target_dom->parentNode->insertBefore($insert_dom, $target_dom->nextSibling);

} else {

return $target_dom->parentNode->appendChild($insert_dom);

}

}

以及如何使用它的示例(特定于您的问题):

$sxe = new SimpleXMLElement('');

// New element to be inserted

$insert = new SimpleXMLElement("");

// Get the last nodeA element

$target = current($sxe->xpath('//nodeA[last()]'));

// Insert the new element after the last nodeA

simplexml_insert_after($insert, $target);

// Peek at the new XML

echo $sxe->asXML();

如果您想/需要解释它是 如何 工作的(代码相当简单,但可能包含外国概念),只需询问即可。

2020-05-29

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值