【发布时间】: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()。首先是在当前图像(<a>)之前添加简单(编辑)图像,然后删除旧节点图像(<a>)。但!它不起作用,它只在每一秒都在做(每个第一个都正确完成)。
那么,让我问一个简单的问题,如何以正确的方式做到这一点?因为我认为下面的代码 (clearPopUpLink) 不够正确...请提出您的解决方案。
【问题讨论】:
-
这是要丢掉anchor但保留图片?
-
是的,我需要删除父
<a>标签,但<img>应该保留在代码中(在同一个地方)。
标签: php parsing domdocument