将DOMXpath转换为HTML字符串
有没有办法将DOMXpath对象转换回HTML?我想替换HTML的一部分将DOMXpath转换为HTML字符串,html,xpath,domxpath,Html,Xpath,Domxpath,有没有办法将DOMXpath对象转换回HTML?我想替换HTML的一部分 <div class='original'>Stuff</div> 我犯了一个错误。如果您有任何建议,我们将不胜感激。看起来像。始终在DOMDocument实例上工作,因此您应该始终保存DOMDocument。请参见下面的工作演示示例: <?php $xml = "<parent><div class='original'>Stuff</div><
<div class='original'>Stuff</div>
我犯了一个错误。如果您有任何建议,我们将不胜感激。看起来像。始终在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();
?>
XPATH->saveHTML();
<?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>