superdee72
superdee72

Reputation: 71

Convert DOMXpath to an HTML string

Is there way to convert the DOMXpath object back to HTML? I would like to replace one section of the HTML

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

replaced with:

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

and then return it back to a valid Xpath. I know that the function DOMDocument::saveHTML exists, but if I do

 XPATH->saveHTML(); 

I get an error. Any advice would be appreciated.

Upvotes: 2

Views: 1972

Answers (1)

har07
har07

Reputation: 89285

Looks like an XY problem. DOMXPath always works on a DOMDocument instance, so you should always save the DOMDocument instead. See a working demo example below :

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

output :

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

Upvotes: 2

Related Questions