[英]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.