0

I have a string of 'source html' and a string of 'replacement html'. In the 'source html' I want to look for a node with a specific class and replace its content with my 'replacement html'. I have tried using the replaceChild method, but this seems to require that I traverse a level up (parentNode).

This doesn't work

  $dom = new DOMDocument;
  $dom->loadXml($sourceHTML);

  $replacement = $dom->createDocumentFragment();
  $replacement->appendXML($replacementHTML);

  $xpath = new DOMXPath($dom);
  $oldNode = $xpath->query('//div[contains(@class,"arrangement--index__field-dato")]')->item(0);
  $oldNode->replaceChild($replacement, $oldNode);

This works, but it's not the content which is being replaced

  $dom = new DOMDocument;
  $dom->loadXml($sourceHTML);

  $replacement = $dom->createDocumentFragment();
  $replacement->appendXML($replacementHTML);

  $xpath = new DOMXPath($dom);
  $oldNode = $xpath->query('//div[contains(@class,"arrangement--index__field-dato")]')->item(0);
  $oldNode->parentNode->replaceChild($replacement, $oldNode);

How do I replace the content or the node I have queried for?

2 Answers 2

1

Instead of replacing the child node, loop over it's children, drop them and insert the new content as child node. Something like

foreach ($oldNode->childNodes as $child)
  $oldNode->removeChild($child);
$oldNode->appendChild($replacement);

This will replace the contents (children) instead of the node itself.

Sign up to request clarification or add additional context in comments.

1 Comment

Rather than remove the child nodes one by one, you could just... $oldNode->nodeValue="";
0

This seems to work!

  $dom = new DOMDocument;
  $dom->loadXml($sourceHTML);

  $replacement = $dom->createDocumentFragment();
  $replacement->appendXML($replacementHTML);

  $xpath = new DOMXPath($dom);
  $oldNode = $xpath->query('//div[contains(@class,"arrangement--index__field-dato")]')->item(0);
  $oldNode->removeChild($oldNode->firstChild);
  $oldNode->appendChild($replacement);

1 Comment

Be aware that there might be multiple child nodes, so you'd better loop over that node and delete all of them. See my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.