Search code examples
phpsimple-html-dom

PHP Simple HTML DOM Parser find direct LI elements


HTML:

<ul>
 <li><a></a>
  <ul>
   <li></li>
   <li></li>
  </ul>
 </li>
 <li>
  ...
 </li>
</ul>

For parent ul:first-of-type, what would be the selector for it's (direct) child li elements, in order to parse the descendant li elements separately?


Solution

  • In Jquery you can simply use this selector : ul > li

    Update:-

    Using Simple DOM:-

    <ul class="listitems">
     <li><a></a>
      <ul>
       <li></li>
       <li></li>
      </ul>
     </li>
     <li>
      ...
     </li>
    </ul>
    

    Simple HTML Dom code to get just the first level li items:

    $html = file_get_html( $url );
    $first_level_items = $html->find( '.listitems', 0)->children();
    
    foreach ( $first_level_items as $item ) {
        ... do stuff ...
    }