PHP DOM如何在子级包含标签和文本节点时删除包装标签 [英] PHP DOM How to remove wrapping tags when children contain tags and text nodes
问题描述
给出此标记
<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)
我已经尝试了以下方法,但是它并不是很有效,我想确保自己走在正确的轨道上,并且不会错过一种更简单的方法.我确实注意到,当我在switch语句(而不是#text)中命中某个标签时,需要添加迭代,以便获得该标签的内容(例如与该标签一起使用).
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);
推荐答案
我创建了一些内容,该内容创建了您要删除的节点内容的副本.似乎不仅仅只是移动节点,而是当我使用 cloneNode
时,新版本看起来更干净了.
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>
这篇关于PHP DOM如何在子级包含标签和文本节点时删除包装标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!