有没有办法将 DOMXpath 对象转换回 HTML?我想替换 HTML 的一部分
<div class='original'>Stuff</div>
替换为:
<div class='replacement'>New Stuff</div>
然后将其返回到有效的 Xpath。我知道 DOMDocument::saveHTML 函数存在,但如果我这样做
XPATH->saveHTML();
我收到一个错误。任何建议将不胜感激。
最佳答案
看起来像an XY problem 。 DOMXPath
始终适用于 DOMDocument
实例,因此您应该始终保存 DOMDocument
。请参阅下面的工作演示示例:
<?php
$xml = "<parent><div class='original'>Stuff</div></parent>";
$doc = new DOMDocument();
$doc->loadXML($xml);
$xpath = new DOMXpath($doc);
//get element to be replaced
$old = $xpath->query("/parent/div")->item(0);
//create new element for replacement
$new = $doc->createElement("div");
$new->setAttribute("class", "replacement");
$new->nodeValue = "New Stuff";
//replace old element with the new one
$old->parentNode->replaceChild($new, $old);
//TODO: save the modified HTML instead of echo
echo $doc->saveHTML();
?>
输出:
<parent><div class="replacement">New Stuff</div></parent>
关于html - 将 DOMXpath 转换为 HTML 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35763504/