繁体   English   中英

使用simplehtmldom仅查找li中的第一个a元素(不包括li中的ul元素)

[英]Find only first a elements in li (excluding ul elements in li) using simplehtmldom

我正在使用simplehtmldom在网站中查找特定元素。

我的密码

 function strpos_arr($haystack) {
    $needle  = array('menu', 'nav');
    if(!is_array($needle)) $needle = array($needle);
    foreach($needle as $what) {
        if(($pos = strpos($haystack, $what))!==false)
            return true;
    }
    return false;
}

$first = true;
foreach($html->find('ul') as $ul){
    if ( strpos_arr($ul->id) OR strpos_arr($ul->class)  ) {
        if ( $first )
        {
            foreach($ul->find('li a') as $li)
            {
                echo $li.'<br>';
            }
            $first = false;
        }
    }
}
?> 

此代码显示所有li元素中的所有链接,包括嵌套在li元素下ul元素内的链接。 我只需要回显li中的main a元素,而不回显ul subs下嵌套的那些元素。

编辑:

所需的行被标记为“我需要的href”

<ul id="parent">
    <li>a href I need<li>
    <li>a href I need<li>
    <li>a href I need<li>
    <li>a href I need<li>
        <ul id="sub">
            <li>a href I DON'T need<li>
            <li>a href I DON'T need<li>
        </ul>
    <li>a href I need<li>
    <li>a href I need<li>
</ul>

我试图使用CSS选择器来过滤元素,但是没有用...所以我使用DOM函数来确保实际元素的父对象是parent

这是一个工作代码,为您提供所需的li节点:

$text = '
        <ul id="parent">
            <li>a href I need</li>
            <li>a href I need</li>
            <li>a href I need</li>
            <li>a href I need</li>
                <ul id="sub">
                    <li>a href I DON\'T need</li>
                    <li>a href I DON\'T need</li>
                </ul>
            <li>a href I need</li>
            <li>a href I need</li>
        </ul>';

//Create a DOM object
$html = new simple_html_dom();

// Load HTML from a string
$html->load($text);

// Find li elmenets within ul tags
$list = $html->find('ul+li');

// Find succeeded
if ($list) {
    echo "<br/> Found ". count($list);

    // Display output as code
    echo "<pre>";

    foreach ($list as $key => $elm) {
        if($elm->parent()->id == "parent") {
            echo htmlentities($elm->outertext);
            echo "<hr/>";
        }
    }

    echo "</pre>";
}
else
    echo "Find function failed !";

PHP小提琴演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM