如何使用Simple HTML DOM Parser解析HTML

时间:2016-03-30 18:59:00

标签: php html simple-html-dom

我有一个网站内容,我想用Simple HTML DOM Parser解析,就像这样:

include('./simple_html_dom.php');

$html = file_get_html('http://www.domain.com/subsite');
$searchResults = $html->find('table[@class=search-results'); 

foreach($searchResults->find('tr[@id^=ad-]') as $tr) {
...
}

这是我现在的代码:

mod_fcgid: stderr: PHP Fatal error:  Call to a member function find() on a non-object in /data/domains/mydomain/web/webroot/path/to/script.php on line 31

问题是我现在收到此错误:

$html

$searchResults = $html->find('.search-results'); 不为空,我已经调试过了。如果我使用此代码进行表格查找,我会得到相同的结果:

function combineDateWithTime(d, t)
{
   return new Date(
    d.getFullYear(),
    d.getMonth(),
    d.getDate(),
    t.getHours(),
    t.getMinutes(),
    t.getSeconds(),
    t.getMilliseconds()
    );
}

可能是什么问题?

1 个答案:

答案 0 :(得分:2)

您的脚本中存在两个问题:

首先,你的搜索模式是错误的(由于拼写错误?):你忘了关闭方括号。这一行:

$searchResults = $html->find('table[@class=search-results]'); 
#                                                        ↑

必须是:

->find()

然后,->find()会返回一个对象数组,因此您必须以这种方式修改下一个foreach( $searchResults[0]->find( 'tr[@id^=ad-]' ) as $tr ) # ↑↑↑

$searchResult = $html->find( 'table[@class=search-results]', 0 ); 
foreach( $searchResult->find( 'tr[@id^=ad-]' ) as $tr )

作为替代方案,您可以使用以下语法:

->find()

{{1}}的第二个参数表示:仅返回第一个匹配的节点(键索引= 0)。

相关问题