如何在PHP中删除重复的嵌套DOM元素? [英] How do you remove duplicate, nested DOM elements in PHP?

查看:98
本文介绍了如何在PHP中删除重复的嵌套DOM元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个带有嵌套标签的DOM树,我想通过删除重复项来清理DOM对象。但是,只有当标签只有一个子标签相同类型例如,



修复< div>< div> 1< / div>< / div> 而不是< div>< div> 1< / div>< div> 2< / div>< / div>



我想知道如何使用 PHP的DOM扩展名。以下是起始代码,我正在寻找帮助找出所需的逻辑。

   
libxml_use_internal_errors(TRUE);

$ html ='< div>< div>< div>< p>这里的一些文本< / p>< / div>< / div>< / div> ;

$ dom = new DOMDocument;
$ dom-> preserveWhiteSpace = false;
$ dom-> formatOutput = true;
$ dom-> loadHTML($ html);

函数dom_remove_duplicate_nodes($ node)
{
var_dump($ node);

if($ node-> hasChildNodes())
{
for($ i = 0; $ i< $ node-> childNodes-> length; $ i ++)
{
$ child = $ node-> childNodes-> item($ i);

dom_remove_duplicate_nodes($ child);
}
}
else
{
//在这里处理?
}
}

dom_remove_duplicate_nodes($ dom);

我收集了一些帮助函数,这样可以更容易地使用像DOM这样的DOM节点。

 函数DOM_delete_node($ node)
{
DOM_delete_children($ node);
return $ node-> parentNode-> removeChild($ node);
}

函数DOM_delete_children($ node)
{
while(isset($ node-> firstChild))
{
DOM_delete_children ($节点 - >则firstChild);
$ node-> removeChild($ node-> firstChild);
}
}

函数DOM_dump_child_nodes($ node)
{
$ output ='';
$ owner_document = $ node-> ownerDocument;

foreach($ node-> childNodes as $ el)
{
$ output。= $ owner_document-> saveHTML($ el);
}
return $ output;
}

函数DOM_dump_node($ node)
{
if($ node-> ownerDocument)
{
return $ node- > ownerDocument-> saveHTML($节点);
}
}


解决方案

你可以使用 DOMDocument DOMXPath 。 XPath特别在你的案例中非常有用,因为你可以轻松地划分逻辑,以选择要删除的元素和删除元素的方式。



首先,将输入归一化。我并不完全清楚你对空白空白的意思,我认为这可能是空文本节点(可能已被删除为 preserveWhiteSpace FALSE 但我不确定)或者如果它们的归一化空格是空的。我选择了第一个(如果是必要的),如果是另一个变体,我留下了一个评论使用什么:

  $ xp = new DOMXPath($ dom); 

//删除空文本节点 - 如果需要,
//(如果删除WS:[normalize-space()=])
foreach($ xp- > query('// text()[])as $ i => $ tn)
{
$ tn-> parentNode-> removeChild($ tn);
}

在这个文本标准化之后,你不应该遇到一个你谈到的问题



下一部分是找到所有与父元素名称相同的元素,哪些是唯一的子元素。这可以再次以xpath表示。如果找到这样的元素,他们的所有子项都被移动到父元素,然后元素也被删除:

  /所有与父元素名称相同的子元素和
//唯一的子元素。
$ r = $ xp-> query('body // * / child :: * [name(。)= name(..)and count(../ child :: *)= 1] );
foreach($ r as $ i => $ dupe)
{
while($ dupe-> childNodes-> length)
{
$ child = $ dupe-> firstChild;
$ dupe-> removeChild($ child);
$ dupe-> parentNode-> appendChild($ child);
}
$ dupe-> parentNode-> removeChild($ dupe);
}

完整演示



正如您在演示中可以看到的那样,这与textnodes和commments是独立的。如果你不想要,例如实际的文本,要计数的表达式需要遍历所有的节点类型。但是我不知道这是否是你的确切需要。如果是这样,这将使所有节点类型的子代数

  body // * / child :: * [name (。)= name(..)and count(../ child :: node())= 1] 

如果您没有预先对空文本节点进行规范化(删除空文本节点),那么这太严格了。选择您需要的一套工具,我认为规范化加上这个严格的规则可能是最好的选择。


Assuming you have a DOM tree with nested tags, I would like to clean the DOM object up by removing duplicates. However, this should only apply if the tag only has a single child tag of the same type. For example,

Fix <div><div>1</div></div> and not <div><div>1</div><div>2</div></div>.

I'm trying to figure out how I could do this using PHP's DOM extension. Below is the starting code and I'm looking for help figuring out the logic needed.

<?php

libxml_use_internal_errors(TRUE);

$html = '<div><div><div><p>Some text here</p></div></div></div>';

$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadHTML($html);

function dom_remove_duplicate_nodes($node)
{
    var_dump($node);

    if($node->hasChildNodes())
    {
        for($i = 0; $i < $node->childNodes->length; $i++)
        {
            $child = $node->childNodes->item($i);

            dom_remove_duplicate_nodes($child);
        }
    }
    else
    {
        // Process here?
    }
}

dom_remove_duplicate_nodes($dom);

I collected some helper functions that might make it easier to work the DOM nodes like JavaScript.

function DOM_delete_node($node)
{
    DOM_delete_children($node);
    return $node->parentNode->removeChild($node);
}

function DOM_delete_children($node)
{
    while (isset($node->firstChild))
    {
        DOM_delete_children($node->firstChild);
        $node->removeChild($node->firstChild);
    }
}

function DOM_dump_child_nodes($node)
{
    $output = '';
    $owner_document = $node->ownerDocument;

    foreach ($node->childNodes as $el)
    {
        $output .= $owner_document->saveHTML($el);
    }
    return $output;
}

function DOM_dump_node($node)
{
    if($node->ownerDocument)
    {
        return $node->ownerDocument->saveHTML($node);
    }
}

解决方案

You can do this quite easily with DOMDocument and DOMXPath. XPath especially is really useful in your case because you easily divide the logic to select which elements to remove and the way you remove the elements.

First of all, normalize the input. I was not entirely clear about what you mean with empty whitespace, I thought it could be either empty textnodes (which might have been removed as preserveWhiteSpace is FALSE but I'm not sure) or if their normalized whitespace is empty. I opted for the first (if even necessary), in case it's the other variant I left a comment what to use instead:

$xp = new DOMXPath($dom);

//remove empty textnodes - if necessary at all
// (in case remove WS: [normalize-space()=""])
foreach($xp->query('//text()[""]') as $i => $tn)
{
    $tn->parentNode->removeChild($tn);
}

After this textnode normalization you should not run into the problem you talked about in one comment here.

The next part is to find all elements that have the same name as their parent element and which are the only child. This can be expressed in xpath again. If such elements are found, all their children are moved to the parent element and then the element will be removed as well:

// all child elements with same name as parent element and being
// the only child element.
$r = $xp->query('body//*/child::*[name(.)=name(..) and count(../child::*)=1]');
foreach($r as $i => $dupe)
{
    while($dupe->childNodes->length)
    {
        $child = $dupe->firstChild;
        $dupe->removeChild($child);
        $dupe->parentNode->appendChild($child);
    }   
    $dupe->parentNode->removeChild($dupe);
}

Full demo.

As you can see in the demo, this is independent to textnodes and commments. If you don't want that, e.g. actual texts, the expression to count children needs to stretch over all node types. But I don't know if that is your exact need. If it is, this makes the count of children across all node types:

body//*/child::*[name(.)=name(..) and count(../child::node())=1]

If you did not normalize empty textnodes upfront (remove empty ones), then this too strict. Choose the set of tools you need, I think normalizing plus this strict rule might be the best choice.

这篇关于如何在PHP中删除重复的嵌套DOM元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆