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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?