domdocument - PHP DOMElement::replaceChild produces fatal error
Get the solution ↓↓↓Source HTML (test.html) is:
<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 to modify this HTML is:
<?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);
Doesn't matter - append newly created $div1_1 to $doc or not. The result is the same - last line produces 'PHP Fatal error: Uncaught DOMException: Not Found Error in ...'.
What's wrong?
Answer
Solution:
Your issue is that$doc
does not have a child which is$div1
. Instead, you need to replace the child of$div1
's parent, which you can access via its property:
$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();
Output:
<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>
Note that you don't need to append$div1_1
to the HTML,replaceChild
will do that for you.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: uncaught error: call to undefined function mysqli_connect()
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.