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

使用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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真