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 关于无人驾驶的航向角
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了