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

时间:2015-10-17 21:52:22

标签: php dom

我希望能够做到相当于

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

但PHP Simple DOM库无法识别“直系后代”选择器>,因此查找<ul>下的所有#foo项,包括嵌套在dom中更深的项。

您会建议什么是获取特定类型的直接后代的最佳方法?

3 个答案:

答案 0 :(得分:3)

您可以使用DomElementFilter在某个Dom分支下获取所需类型的节点。这在这里描述:

PHP DOM: How to get child elements by tag name in an elegant manner?

或者对所有childNodes进行常规循环,然后根据自己的标记名称进行过滤:

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

答案 1 :(得分:1)

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;

答案 2 :(得分:0)

只是为了分享我在相关帖子中找到的解决方案,简而言之: &#34;使用PHP简单DOM解析器找到直接后代&#34;适用于......

... 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
        }
    }

请注意,您必须使用单斜线&#34; / &#34;在xpath中只查找直接后代。