您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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('<root><nodeA/><nodeA/><nodeA/><nodeC/><nodeC/><nodeC/></root>');
// New element to be inserted
$insert = new SimpleXMLElement("<nodeB/>");
// 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();

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

php 2022/1/1 18:18:01 有492人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶