【问题标题】:PHP DOMDocument replaceChildPHP DOMDocument replaceChild
【发布时间】:2013-06-16 17:06:10
【问题描述】:

我无法使用此方法。

我有这个 PHP 代码:

        $dom = new \DOMDocument();
        $dom->loadHTML($this->_html);

        $newD = $viewElement->replaceHtml();


        $oe = $dom->getElementById("{{ALViewElement_resume}}");
        $ne = $newD->getElementById("resume");


        echo $dom->saveHTML();
        echo $dom->saveHTML($oe);
        echo $newD->saveHTML($ne);
        echo $dom->saveHtml($oe->parentNode);
        $oe->parentNode->replaceChild($ne, $oe);

        echo $dom->saveHTML($ne);
        echo $dom->saveHTML();

所以我创建了一个 DOMDocument,并加载了一些 html。然后我调用$viewElement->replaceHtml(),这是我在其他地方的一个函数,它返回另一个 DOMDocument 对象。

然后$oe 是我最初在传入的 html 中的元素,而 $ne 是在我的 replaceHtml 调用中创建的 DOMDocument 中的元素。我想用$ne 替换$oe

然后我有所有这些回声。第一个会显示$dom 的开头,这是正确的。

下一个将显示原始元素(我要替换的那个),这是正确的。注意 id 以 {{ALViewElement_.

开头

接下来向您展示我想要替换原始元素的元素。请注意,除了 id 不是以 ALViewElement 开头之外,它就像是一样的东西。 不,我不是在寻找可以很容易地用 DOMDocument 更改 id 的答案,因为这不是我要在这里寻找的。​​strong>

下一个调用显示原始元素的 parentNode。它只是一个 html 片段,所以实际上没有 parentNode。这会打印出来。注意 {{ALViewElement_ id.

然后我调用 replace child。

然后接下来的两个回显什么也不打印。 replaceChild 不起作用,我失去了一切。

为什么这不起作用?我错过了什么?

编辑:忘记了 HTML。

我把它们放在一个 jsFiddle 中,所以很容易看到:https://jsfiddle.net/jDPTC/

【问题讨论】:

  • 我在 DOMDocument 之前看到很多带有 `\` 的帖子。这是什么意思?
  • 这是由于我的命名空间。
  • @user1513171 请参见php.net/manual/en/language.namespaces.rationale.php - 需要反斜杠来引用全局命名空间中的类
  • 好的,谢谢。我向你保证这不是问题。我可以调用所有其他方法就好了。

标签: php dom replace children


【解决方案1】:

你应该先克隆你的新节点,例如

$oe->parentNode->replaceChild($ne->cloneNode(true), $oe);

https://www.php.net/manual/en/domnode.clonenode.php

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-15
    • 1970-01-01
    • 2012-01-10
    • 2011-02-20
    • 1970-01-01
    相关资源
    最近更新 更多