【问题标题】:DOMDocument and delete parent tagDOMDocument 和删除父标签
【发布时间】:2014-09-03 00:33:41
【问题描述】:

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

libxml_use_internal_errors(true); // disable errors

$oHtml = new DOMDocument();

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

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

<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() 完成所有“图像”时,它没有带有标签的旧代码?我尝试使用(第一次开始调查时)->insertBefore(),之后使用->removeChild()。首先是在当前图像(&lt;a&gt;)之前添加简单(编辑)图像,然后删除旧节点图像(&lt;a&gt;)。但!它不起作用,它只在每一秒都在做(每个第一个都正确完成)。

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

【问题讨论】:

  • 这是要丢掉anchor但保留图片?
  • 是的,我需要删除父 &lt;a&gt; 标签,但 &lt;img&gt; 应该保留在代码中(在同一个地方)。

标签: php parsing domdocument


【解决方案1】:

嗯,我会为此使用受托方 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();

【讨论】:

    猜你喜欢
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多