tolborg
tolborg

Reputation: 612

Replace content of node using PHP and XPath

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?

Upvotes: 0

Views: 2015

Answers (2)

Jens Erat
Jens Erat

Reputation: 38732

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.

Upvotes: 1

tolborg
tolborg

Reputation: 612

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

Upvotes: 0

Related Questions