How to use Simple HTML Dom to get an adjacent sibling element?

3.1k views Asked by At

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

There are 1 answers

0
adeneo On BEST ANSWER

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();

}