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

JAy*_*een 3 php dom

鉴于此标记

<badtag>
  This is the title and <em>really</em> needs help
<badtag>
Run Code Online (Sandbox Code Playgroud)

我需要移除包装器,但在不丢失标签的情况下执行此操作,如果我只是执行以下操作,就会发生这种情况:

dom->createTextNode(currentNode->nodeValue)
Run Code Online (Sandbox Code Playgroud)

我尝试了以下方法,但效果不佳,我想确保自己走在正确的轨道上,不会错过更简单的方法。我确实注意到,当我在 switch 语句(而不是 #text)中点击标签时,我需要添加迭代,以便我获得标签的内容(例如使用标签)。

      $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);
Run Code Online (Sandbox Code Playgroud)

Nig*_*Ren 5

我创建了一些东西,它创建了要删除的节点内容的克隆。它似乎不喜欢只是移动节点,当我使用它时cloneNode,新版本似乎更干净。

<?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();
Run Code Online (Sandbox Code Playgroud)

对于我使用的小样本,输出是...

<?xml version="1.0"?>
<DATA>

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

</DATA>
Run Code Online (Sandbox Code Playgroud)