Search code examples
phpfindsimple-html-dom

In simple_html_dom how do I find first-level <divs> within div.classname


I'm using simple_html_dom
I have some html in a php var $text:

<div class="aClass">
  <div>
    ...some html
    <div class="anotherClass">
      ..more html
    </div>
  </div>
  <div>
    ...some html
    <div class="anotherClass">
      ..more html
    </div>
  </div>
</div>

I know I can select the outermost div with $text->find("div.aClass")
Instead I want to select all the first level divs within that div so I can process them as part of a foreach loop
Something like:

foreach ($text->find("div.aClass div") as $myDiv) {
// do stuff with $myDiv
}

but that seems to select all divs, including those with class="anotherClass"

Any help much appreciated - thanks!


Solution

  • You can use then child combinator selector > which selects only the elements that are direct children of a parent.

    div.aClass > div
    

    For example

    $html = <<<HTML
    <div class="aClass">
      <div>
        ...some html
        <div class="anotherClass">
          ..more html
        </div>
      </div>
      <div>
        ...some html
        <div class="anotherClass">
          ..more html
        </div>
      </div>
    </div>
    HTML;
    
    $text = str_get_html($html);
    
    foreach ($text->find("div.aClass > div") as $myDiv) {
        echo $myDiv->innertext() . PHP_EOL;
    }
    

    Output

     ...some html     <div class="anotherClass">       ..more html     </div>   
     ...some html     <div class="anotherClass">       ..more html     </div>