doudang2537
2014-03-08 21:10
浏览 102
已采纳

使用PHP和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?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douru5373 2014-03-08 21:28
    已采纳

    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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • doubi9999 2014-03-08 21:22

    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);
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题