首先只找到 li 中的元素(不包括 li 中的 ul 元素),使用 simplehtmldom


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 中的主要 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小提琴演示