首页 > 解决方案 > PHP DOMElement::replaceChild 产生致命错误

问题描述

源 HTML (test.html) 是:

<html lang="ru">
  <head>
  <meta charset="UTF-8">
    <title>PHP Test</title>
  </head>
  <body>
    <h1>Test page</h1>
    <div>
        <div id="to-replace-1">Test content 1</div>
    </div>
  </body>
</html>

修改这个 HTML 的 PHP 是:

<?php 
$str = file_get_contents('test.html');
$doc = new DOMDocument();
@$doc->loadHTML($str);

$div1 = $doc->getElementById('to-replace-1');
echo $div1->nodeValue;  // Success - 'Test content 1'
$div1_1 = $doc->createElement('div');
$div1_1->nodeValue = 'Content replaced 1';
$doc->appendChild($div1_1);
$doc->replaceChild($div1_1, $div1); 

没关系 - 是否将新创建的 $div1_1 附加到 $doc。结果是一样的——最后一行产生“PHP 致命错误:未捕获的 DOMException:在 ... 中未找到错误”。

怎么了?

标签: phpdomdocument

解决方案


你的问题是$doc没有孩子$div1。相反,您需要替换 的$div1父级的子级,您可以通过其parentNode属性访问它:

$doc = new DOMDocument();
$doc->loadHTML($str, LIBXML_HTML_NODEFDTD);

$div1_1 = $doc->createElement('div');
$div1_1->nodeValue = 'Content replaced 1';

$div1 = $doc->getElementById('to-replace-1');
$div1->parentNode->replaceChild($div1_1, $div1); 
echo $doc->saveHTML();

输出:

<html lang="ru">
  <head>
  <meta charset="UTF-8">
    <title>PHP Test</title>
  </head>
  <body>
    <h1>Test page</h1>
    <div>
        <div>Content replaced 1</div>
    </div>
  </body>
</html>

3v4l.org 上的演示

请注意,您不需要附加$div1_1到 HTML,replaceChild它将为您完成。


推荐阅读