ul") But the PHP Simpl...">

Find immediate children using PHP Simple DOM parser

I would like to be able to make an equivalent

$html->find("#foo>ul")

But the PHP Simple DOM library does not recognize the “immediate descendant” selector >and therefore finds all <ul>elements under #foo, including those deeper nested in dom.

What would you recommend as the best way to capture immediate descendants of a particular type?

+4
source share
3 answers

You can use DomElementFilter to select the desired node type under a certain Dom branch. This is described here:

PHP DOM: How to get children by tag name in an elegant way?

:

foreach ($parent->childNodes as $node)
    if ($node->nodeName == "tagname1")
        ...
+3

HTML

<div id="foo">
    <ul>
        <li>1</li>
    </ul>       
    <ul>
        <li>2</li>
    </ul>       
    <ul>
        <li>3</li>
    </ul>       
</div>

PHP, FIRST <ul>

echo $html->find('#foo>ul', 0);

<ul>
    <li>1</li>
</ul>

1 <ul>

echo $html->find('#foo>ul', 0)->plaintext;
+1

, , : " PHP Simple DOM parser" ...

... PHP Simple DOM:

    //if there is only one div containing your searched tag
    foreach ($html->find('div.with-given-class')[0]->children() as $div_with_given_class) {
        if ($div_with_given_class->tag == 'tag-you-are-searching-for') {
        $output [] = $div_with_given_class->plaintext; //or whatever you want
        }
    }


    //if there are more divs with a given class (better solution)
    $all_divs_with_given_class = 
        $html->find('div.with-given-class');

    foreach ($all_divs_with_given_class as $single_div_with_given_class) {
        foreach ($single_div_with_given_class->children() as $children) {
            if ($children->tag == 'tag-you-are-searching-for') {
                $output [] = $children->plaintext; //or whatever you want
            }
        }
    } 

... PHP DOM/xpath:

    $all_divs_with_given_class =     
        $xpath->query("//div[@class='with-given-class']/tag-you-are-searching-for");

    if (!is_null($all_divs_with_given_class)) {
        foreach ($all_divs_with_given_class as $tag-you-are-searching-for) {
            $ouput [] = $tag-you-are-searching-for->nodeValue; //or whatever you want
        }
    }

, "/" xpath .

0

Source: https://habr.com/ru/post/1612088/


All Articles