PHP DOMElement::replaceChild 产生致命错误

PHP DOMElement::replaceChild produces fatal error

来源 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>

PHP修改这个HTML为:

<?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 Fatal error: Uncaught DOMException: Not Found Error in ...'.

怎么了?

您的问题是 $doc 没有 child 即 $div1。相反,您需要替换 $div1 的 parent 的 child,您可以通过 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>

Demo on 3v4l.org

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