douxingti9307 2015-06-09 12:50
浏览 71
已采纳

如何使用Simple HTML Dom获取相邻的兄弟元素?

I am using Simple HTML Dom parser to get an element from an HTML string using it's class name, like:

foreach ($html->find('div[class=news-div]')) {
    $news = $news-div;
}

But I also need to get two elements (one is span and the other is a) that occur just before the $news, but they don't have an id that can be predicted because it is calculated dynamically, and they don't have a unique class name.

How can I extract the two adjacent elements occurring before $news-div?

  • 写回答

1条回答 默认 最新

  • dra87370 2015-06-09 12:55
    关注

    SimpleHTML has prev_sibling and next_sibling methods

    $elems = $html->find('div[class=news-div]');
    
    foreach ( $elems as $news ) {
    
        $prev_span = $news->prev_sibling();
    
        $prev_a    = $prev_span->prev_sibling();
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?