使用PHP简单DOM解析器查找直接后代



我希望能够做与

相同的事情
$html->find("#foo>ul")

但是PHP Simple DOM库不识别"直接后代"选择器>,因此在#foo下找到所有<ul>项,包括那些嵌套在DOM中的项。

您认为获取特定类型的直系后代的最佳方法是什么?

您可以使用DomElementFilter来获取某些Dom分支下所需的节点类型。如下所示:

PHP DOM:如何以优雅的方式通过标签名获得子元素?

或者在所有childnode上执行常规循环,然后根据它们的标签名称自己过滤它们:

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

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>

但是如果你想从第一个<ul>

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

只是分享我在相关帖子中找到的解决方案,并将其概括:"使用PHP简单DOM解析器查找直接后代"适用于…

PHP简单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中使用单斜杠"/"来查找直接后代。

最新更新