DOMDocument并删除父标记

时间:2014-07-12 14:09:00

标签: php parsing domdocument

我们通过url加载html。之后创建DOMDocument

libxml_use_internal_errors(true); // disable errors

$oHtml = new DOMDocument();

if (!$oHtml->loadHTML($this->getHtml($aData['href']))) {
    return false;
}

下一步是删除fancybox或其他popUp链接......在我们的例子中,图像代码是

<a onclick="return hs.expand(this)" href="http://domain.com/uploads/09072014106.jpg">
    <img title="Some title" alt="Some title" src="http://domain.com/uploads/thumbs/09072014106.jpg">
</a>

我们为它执行我们的方法......

$this->clearPopUpLink($oHtml); // delete parent <a tag....

...方法

private function clearPopUpLink($oHtml)
    {
        $aLink = $oHtml->getElementsByTagName('a');
        if (!$aLink->length) {
            return false;
        }

        for ($k = 0; $k < $aLink->length; $k++) {
            $oLink = $aLink->item($k);

            if (strpos($oLink->getAttribute('onclick'), 'return hs.expand(this)') !== false) {
//              <a onclick="return hs.expand(this)" href="http://domain.com/uploads/posts/2014-07/1405107411_09072014106.jpg">
//                  <img title="Some title" alt="Some title" src="http://domain.com/uploads/posts/2014-07/thumbs/1405107411_09072014106.jpg">
//              </a>
                $oImg = $oLink->firstChild;
                $oImg->setAttribute('src', $oLink->getAttribute('href')); // set img proper src

//                $oLink->parentNode->removeChild($oLink);
//                $oLink->parentNode->replaceChild($oImg, $oLink);
                $oLink->parentNode->insertBefore($oImg); // replacing!?!?!?!

//                echo $oHtml->ownerDocument->saveHtml($oImg);
            }
        }
    }

现在问题......这段代码正在运行但我不明白为什么!为什么当clearPopUpLink()完成所有“图像”时,它没有带标签的OLD代码?我尝试使用(在开始调查的第一时间) - &gt; insertBefore(),之后 - &gt; removeChild()。首先是添加简单(已编辑)图像BEFOR当前图像(带<a>),之后删除旧节点图像(带<a>)。但!它不起作用,它只在每一秒做(每个第一次都正确完成)。

那么,让我问一个简单的问题,如何以正确的方式做到这一点?因为我认为下面的代码(clearPopUpLink)不够正确...请建议您的解决方案。

1 个答案:

答案 0 :(得分:2)

嗯,我会使用受托者XPath来确保锚被删除;你所展示的代码并没有完全证明这一点(我还没有测试过它)。

$xpath = new DOMXPath($doc);

foreach ($xpath->query('//a[contains(@onclick, "return hs.expand(this)")]/img') as $img) {
        $anchor = $img->parentNode;

        $anchor->parentNode->insertBefore($img, $anchor); // take image out
        $anchor->parentNode->removeChild($anchor); // remove empty anchor
}

echo $doc->saveHTML();