dongwei2610 2014-10-03 14:34
浏览 22
已采纳

php基于getAttribute从html中删除标签

How can I limit which link tag is removed by specifying $tag->getAttribute('rel') = "icon"? I tried adding a simple if statement to the $remove[] $tags as $tag; line...code ran through, but the link with rel="icon" line was not at all removed.

So in this example the whole link tag should be removed from the html:

<link rel="icon" type="image/png" href="/images/favicon.ico" />


$html = file_get_contents($url);
$dom = new DOMDocument();
$dom->loadHTML($html);

$tags = $dom->getElementsByTagName('link');

$remove = [];
foreach($tags as $tag) {
    $remove[] = $tag;
}

foreach ($remove as $tag) {
    $tag->parentNode->removeChild($tag); 
}

UPDATE Answer here: @prodigitalson provided the following which initially did not work:

$html = file_get_contents($url);
$dom = new DOMDocument();
$dom->loadHTML($html);
$finder = new DOMXpath($dom);
$tags = $finder->query('//link[@rel="icon"]');

foreach ($tags as $tag)
{
$tag->parentNode->removeChild($tag); 
}

by adding the following line as the last line of the code...worked perfect.

$html = $dom->saveHTML();
  • 写回答

2条回答 默认 最新

  • duanren9163 2014-10-03 14:40
    关注

    You can get these all with an xpath:

    $html = file_get_contents($url);
    $dom = new DOMDocument();
    $dom->loadHTML($html);
    $finder = new DOMXpath($dom);
    $tags = $finder->query('//link[@rel="icon"]');
    $toRemove = array();
    
    foreach ($tags as $tag)
    {
      $toRemove[] = $tag;
    }
    
    // with array walk
    array_walk(function($elem) { $elem->parentNode->removeChild($elem); }, $toRemove);
    
    // with foreach
    foreach ($toRemove as $tag) {
      $tag->parentNode->removeChild($tag);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题