1

我有这个带有开关的程序:

$htmlContent = file_get_contents('http://somesite.com');
$htmlDOM->loadHTML( $htmlContent );
$htmlXPath = new DOMXPath( $htmlDOM );

for($i = 0; $i <= 16; $i++ ) {
    switch($i) {
        case 0:
            $link = utf8_decode($htmlXPath->query('/html/body/div[2]/div[2]/div/div/div/div/div[2]/div/a')->item(0)->getAttribute('href'));
            break;
        case 1:
            $link = utf8_decode($htmlXPath->query('/html/body/div[2]/div[2]/div/div/div/div/ul/li/div/a')->item(0)->getAttribute('href'));
            break;
        default:
            $link = utf8_decode($htmlXPath->query('/html/body/div[2]/div[2]/div/div/div/div/ul/li[' . $i . ']/div/a')->item(0)->getAttribute('href'));
            break;
    }
}

对于案例 0 和案例 1 的工作方式与预期相同,但默认情况下会引发此错误:

PHP Fatal error:  Call to a member function getAttribute() on a non-object

我可以想象它是因为 $i 而发生的,但是我该如何解决这个问题呢?

感谢帮助!

4

1 回答 1

1

查询很可能找不到任何内容并返回零长度节点列表。尝试从空列表中获取节点返回 false,而不是对象。

不要假设查询成功,而是使用中间持有者来检查:

$nodes = $htmlXPath->query('/html/body/div[2]/div[2]/div/div/div/div/div[2]/div/a');
if ($nodes->length > 0) {
   $link = $nodes->item(0)->getAttribute('href'));
}
于 2012-01-13T04:24:06.497 回答