douyu2817 2017-10-16 16:21
浏览 82
已采纳

PHP DOM如何在子项包含标记和文本节点时删除包装标记

Given this markup

<badtag>
  This is the title and <em>really</em> needs help
<badtag>

I need to remove the wrapper, but do it without losing the tag, which is what happens if I simply do something like:

dom->createTextNode(currentNode->nodeValue)

I've tried the following, but it's not quite working and I want to make sure I'm on the right track and not missing an easier way. I do note that I need to add iteration when I hit a tag in the switch statement (rather than #text) so that I get the contents of the tag (such as with the tag).

      $l = $origElement->childNodes->length;
      $new = [];
      for ($i = 0; $i < $l; ++$i) {
        $child = $origElement->childNodes->item($i);
        switch ($child->nodeName) {
          case '#text':
            $new[] = $dom->createTextNode($origElement->textContent);
            break;
          default:
            $new[] = $child;
            break;
        }
      }
      foreach ($new as $struct) {
        $parentNode->insertBefore($struct, $origElement);
      }
      $origElement->parentNode->removeChild($origElement);
  • 写回答

1条回答 默认 最新

  • dongzhuanlei0768 2017-10-16 17:50
    关注

    I've created something which creates a clone of the content of the node you want to remove. It didn't seem to like just moving the nodes, and when I use cloneNode instead, the new version seemed a lot cleaner.

    <?php
    error_reporting ( E_ALL );
    ini_set ( 'display_errors', 1 );
    
    $xml = <<<EOB
    <DATA>
    <badtag>
      This is the title and <em>really</em> needs help
    </badtag>
    </DATA>
    EOB;
    
    $dom = new DOMDocument();
    $dom->loadXML($xml);
    
    $origElement = $dom->getElementsByTagName("badtag")[0];
    $newParent = $origElement->parentNode;
    foreach ( $origElement->childNodes as $child ){
        $newParent->insertBefore($child->cloneNode(true), $origElement);
    }
    $newParent->removeChild($origElement);
    echo $dom->saveXML();
    

    For the small sample I've used, the output is...

    <?xml version="1.0"?>
    <DATA>
    
      This is the title and <em>really</em> needs help
    
    </DATA>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看