phpweb-scrapingdomsimple-html-dom

Scrape HTML & count children using Simple HTML DOM


I'm trying to collect data from a website, and want to count the amount of elements in another element. Targeting different DOM elements works fine, but for some reason the $count variable in the example below stays at "0". I'm probably missing something really silly, but I can't seem to find it.

The HTML on the website is as follows:

<div id="list_options">
    <div class="list_mtgdef_option pointer">
        <div class="list_mtgdef_foildesc shadow">
        </div>
        <div class="list_mtgdef_stock tooltip">
            <div class="list_mtgdef_stock_left">
                <span class="foil008469_1 block  "></span>
                <span class="foil008469_2 block  transparency_25"></span>
            </div>
            <div class="list_mtgdef_stock_right">
                <span class="008469_8 block  "></span>
                <span class="008469_7 block  "></span>
                <span class="008469_6 block  "></span>
                <span class="008469_5 block  "></span>
                <span class="008469_4 block  "></span>
                <span class="008469_3 block  "></span>
                <span class="008469_2 block  "></span>
                <span class="008469_1 block  "></span>
            </div>
        </div>
    </div>
</div>

And this is the php I'm using:

$array = array();

foreach($html->find('#list_options .list_mtgdef_option') as $element) {
    $count = 0;

    foreach($element->find('.list_mtgdef_stock', 0)->childNodes(1)->childNodes as $node) {
        if(!($node instanceof \DomText))
            $count++;
    }

    $row = array(
        'stock' => strval($count)
    );

    array_push($array, $row);

}
echo json_encode($array);

Solution

  • You can just do:

    count($element->find('.list_mtgdef_stock > *[2] > *'))
    //=>8