PHP使用DOMXPath去除标记并删除节点

时间:2014-10-31 14:39:29

标签: php html xpath domdocument

我正在尝试使用DOMDocument,但我遇到了一些问题。我有一个这样的字符串:

Some Content to keep
<span class="ice-cts-1 ice-del" data-changedata="" data-cid="5" data-time="1414514760583" data-userid="1" data-username="Site Administrator" undefined="Site Administrator">
     This content should remain, but span around it should be stripped
</span> 
     Keep this content too
<span>
     <span class="ice-cts-1 ice-ins" data-changedata="" data-cid="2" data-time="1414512278297" data-userid="1" data-username="Site Administrator" undefined="Site Administrator">
         This whole node should be deleted
     </span>
</span>

我想要做的是,如果跨度有类似ice-del的类,请保留内部内容但删除span标记。如果它有ice-ins,请删除整个节点。

如果它只是一个空的范围<span></span>,也可以删除它。这是我的代码:

//this get the above mentioned string
$getVal = $array['body'][0][$a];
$dom = new DOMDocument;
$dom->loadHTML($getVal );
$xPath = new DOMXPath($dom);
$delNodes = $xPath->query('//span[@class="ice-cts-1 ice-del"]');
$insNodes = $xPath->query('//span[@class="ice-cts-1 ice-ins"]');

foreach($insNodes as $span){
    //reject these changes, so remove whole node
    $span->parentNode->removeChild($span);
}

foreach($delNodes as $span){
    //accept these changes, so just strip out the tags but keep the content
}

$newString = $dom->saveHTML();

因此,我的代码可以删除整个span节点,但是如何获取节点并删除它标记但保留其内容?

另外,我如何删除并清空span?我确定我可以使用正则表达式或替换来做到这一点,但我有点想用dom做到这一点。

感谢

2 个答案:

答案 0 :(得分:4)

不,我不推荐使用正则表达式,我强烈建议您使用这个漂亮的HTML Parser来构建现有的内容。在这种情况下,您可以使用->replaceChild

$dom = new DOMDocument;
$dom->loadHTML($getVal);
$xPath = new DOMXPath($dom);

$spans = $xPath->query('//span');
foreach ($spans as $span) {
    $class = $xPath->evaluate('string(./@class)', $span);
    if(strpos($class, 'ice-ins') !== false || $class == '') {
        $span->parentNode->removeChild($span);
    } elseif(strpos($class, 'ice-del') !== false) {
        $span->parentNode->replaceChild(new DOMText($span->nodeValue), $span);
    }
}

$newString = $dom->saveHTML();

答案 1 :(得分:0)

从DOM树中删除任何HTML标记的更通用的解决方案使用此方法;

$dom = new DOMDocument;
$dom->loadHTML($getVal);
$xPath = new DOMXPath($dom);

$tagName = $xPath->query('//table'); //use what you want like div, span etc.
foreach ($tagName as $t) {
    $t->parentNode->removeChild($span);
}

$newString = $dom->saveHTML();

示例html:

<html>
    <head></head>
    <body>
       <table>
        <tr><td>Hello world</td></tr>
       </table>
    </body>
</html>

处理后输出;

<html>
    <head></head>
    <body></body>
</html>