Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple HTML DOM - Child Selectors (CSS)

I am trying to select a (direct) child of parents div.element using the > combinator, but it's failing.

HTML:

<div class="element">
    <p>test</p>
</div>

<div class="element">
    <div class="selected">
        <p>test2</p>
    </div>
</div>

PHP:

$html->find('div.element > p', 0);

I am looking to select the direct p element.

If it's a nested descendant - it shouldn't return anything, but it returns test2.

How can I write it to return test, but not test2? Thanks

UPDATE: The general consensus here on SO seems to be that Simple HTML DOM is bad. I ended up writing my code using PHP's DOMDocument as suggested by Phil. I did test out nevermind's solution and it did work as well. Thanks for all the help and Happy Coding

like image 957
RisingSun Avatar asked Oct 31 '22 21:10

RisingSun


1 Answers

Well, this should (must, actually:)) work (tested on 4 divs):

foreach($html->find('div.element') as $element) {


$paragraph=$element->find('p',0);

    if($paragraph==$element->first_child())
    echo $paragraph;

}
like image 59
sinisake Avatar answered Nov 09 '22 17:11

sinisake