How to imitate child selector with Simple HTML DOM?

后端 未结 2 367
粉色の甜心
粉色の甜心 2021-01-23 09:03

Fellas!

I have one nasty page to parse but can\'t figure out how to extract correct data blocks from it using Simple HTML DOM, because it has no CSS child selector suppo

相关标签:
2条回答
  • 2021-01-23 09:44

    I had the same issue, and used the children method to grab just the first level items.

    <ul class="my-list">
        <li>
            <a href="#">Some Text</a>
            <ul>
                <li><a href="#">Some Inner Text</a></li>
                <li><a href="#">Some Inner Text</a></li>
                <li><a href="#">Some Inner Text</a></li>
                <li><a href="#">Some Inner Text</a></li>
            </ul>
        </li>
        <li>
            <a href="#">Some Text</a>
            <ul>
                <li><a href="#">Some Inner Text</a></li>
                <li><a href="#">Some Inner Text</a></li>
                <li><a href="#">Some Inner Text</a></li>
                <li><a href="#">Some Inner Text</a></li>
            </ul>
        </li>
    </ul>
    

    And here's the Simple HTML Dom code to get just the first level li items:

    $html = file_get_html( $url );
    $first_level_items = $html->find( '.my-list', 0)->children();
    
    foreach ( $first_level_items as $item ) {
        ... do stuff ...
    }
    
    0 讨论(0)
  • 2021-01-23 09:57

    Simple example with php DOM:

    $dom = new DomDocument;
    $dom->loadHtml('
    <ul class="ul-block">
       <li>a</li>
       <li>b</li>
       <li>
          <ul>
             <li>c</li>
          </ul>
       </li>
    </ul>
    ');
    
    $xpath = new DomXpath($dom);
    foreach ($xpath->query('//ul[@class="ul-block"]/li') as $liNode) {
        echo $liNode->nodeValue, '<br />';
    }
    
    0 讨论(0)
提交回复
热议问题