Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将DOMXpath转换为HTML字符串_Html_Xpath_Domxpath - Fatal编程技术网

将DOMXpath转换为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><

有没有办法将DOMXpath对象转换回HTML?我想替换HTML的一部分

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