php - 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:在 ... 中未找到错误”。
怎么了?
解决方案
你的问题是$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>
请注意,您不需要附加$div1_1
到 HTML,replaceChild
它将为您完成。
推荐阅读
- android - 在 OpenCV 中应用 GrabCut 算法后获取相同的图像
- wordpress - 页面不会在 wordpress 中重定向到 https
- google-chrome - Chrome:SSO 上的 ERR_UNSAFE_REDIRECT
- java - 如何使用 JavaFX 使我的“inputPane”居中
- python - 在列表中使用 Python 变量
- javascript - 无限可滚动的div?
- symfony - 如何在 symfony4 中同时拥有 prod 和 dev ENV
- spring - Spring MVC 中的@Controller 和@RequestMapping 有什么区别?
- android - 使用没有纵横比的缩放手势缩放位图(水平或垂直)
- javascript - 使用 Google Document 的段落标题样式设置 Drive 文件名