douxue4242 2014-12-02 22:05
浏览 63

如何使用php HTML DOMDocument类删除元素及其子元素

I'm relatively new to php's HTMLDOMDocument class.

I'm doing something like this:

$html = getHTML();

$htmlDOM = new DOMDocument('5.0', 'utf-8');
libxml_use_internal_errors(true);
$htmlDOM->loadHTML(mb_convert_encoding(($html), 'HTML-ENTITIES', 'UTF-8'));
libxml_clear_errors();

Unfortunately all the elements that are retrieved has classes, not IDs. Retrieving elements by Id or Tags are pretty straightforward...

But, how do I retrieve a few elements inside with a specific class (eg: post-hover) and then delete them from $htmlDOM ?

  • 写回答

1条回答 默认 最新

  • duanhuan3705 2014-12-02 23:13
    关注

    No idea why they haven't added a getElementsByClassName yet. But you can use xpath to find the elements instead (taken from here):

    $finder = new DomXPath($dom);
    $classname = "my-class";
    $nodes = $finder->query("//*[contains(@class, '$classname')]");
    

    Then simply loop through and delete:

    foreach($nodes as $node){
        $node->parentNode->removeChild($node);
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看