将DOMXpath转换为HTML字符串

时间:2016-03-03 04:55:08

标签: html xpath domxpath

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

<div class='original'>Stuff</div>

替换为:

<div class='replacement'>New Stuff</div>

然后将其返回到有效的Xpath。我知道函数DOMDocument :: saveHTML存在,但如果我这样做

 XPATH->saveHTML(); 

我收到错误。任何建议将不胜感激。

1 个答案:

答案 0 :(得分:1)

看起来像an XY problemDOMXPath始终适用于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();
?>

<强> eval.in demo

输出

<parent><div class="replacement">New Stuff</div></parent>