繁体   English   中英

PHP简单的HTML DOM找到后找到

[英]PHP simple html dom find after find

如何在find循环中执行find循环? 我一直在获取PHP Notice: Trying to get property of non-object在行echo $li->find('span')->innertext; PHP Notice: Trying to get property of non-object echo $li->find('span')->innertext;

// get the html
$html = file_get_html('<url>');

// loop through the required element
foreach($html->find('body') as $body){

    // loop through the selected element
    $lis = $body->find('li');

    foreach($lis as $li){
        // loop through li to get the required span
        echo $li->find('span')->innertext;
    }
}

我正在使用简单HTML Dom http://simplehtmldom.sourceforge.net/manual.htm

您收到错误消息,因为查找span返回一个数组;如果使用第二个参数,则返回null

// get the html
$html = file_get_html('<url>');

// loop through the required element
foreach($html->find('body') as $body){

// loop through the selected element
$lis = $body->find('li');

    foreach($lis as $li){
        // loop through li to get the required span
        $span = $li->find('span', 0);
        if(null !== $span){
            echo $span->innertext;
        }
     }
}

而且我认为您可能要检查遍历dom

您可以尝试以下操作:

// get the html
$html = file_get_html('<url>');

// loop through the required element
foreach($html->find('li > span') as $span){

    echo span->innertext;
}

下面提供了一些示例(来自站点)以阐明您的理解:

// Find all <li> in <ul> 
$es = $html->find('ul li');

// Find Nested <div> tags
$es = $html->find('div div div'); 

// Find all <td> in <table> which class=hello 
$es = $html->find('table.hello td');

// Find all td tags with attribite align=center in table tags 
$es = $html->find(''table td[align=center]');

您应该阅读文档以更好地理解。 另外,在访问任何属性之前检查项目,例如: if ($someItem)等。

暂无
暂无

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

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