[英]PHP simple html dom find after find
How do I execute find loop within find loop ? 如何在find循环中执行find循环? I keep getting
PHP Notice: Trying to get property of non-object
in line echo $li->find('span')->innertext;
我一直在获取
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;
}
}
I am using Simple Html Dom http://simplehtmldom.sourceforge.net/manual.htm 我正在使用简单HTML Dom http://simplehtmldom.sourceforge.net/manual.htm
You get the error because the find span
returns an array or null if the second parameter is used 您收到错误消息,因为查找
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;
}
}
}
And I think you may want to check traverse the dom 而且我认为您可能要检查遍历dom
You may try something like the following: 您可以尝试以下操作:
// get the html
$html = file_get_html('<url>');
// loop through the required element
foreach($html->find('li > span') as $span){
echo span->innertext;
}
Some examples (from site) are given below to clarify your understanding: 下面提供了一些示例(来自站点)以阐明您的理解:
// 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]');
You should read the docs for better understanding. 您应该阅读文档以更好地理解。 Also, check the item before accessing any property, ie:
if ($someItem)
and so on. 另外,在访问任何属性之前检查项目,例如:
if ($someItem)
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.