简体   繁体   English

PHP中DOMNode的getAttribute()不适用于DOMXPath查询中的变量。 为什么?

[英]getAttribute() of DOMNode in PHP doesn't work with a variable in DOMXPath query. Why?

I have this program with a switch: 我有一个带有开关的程序:

$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;
    }
}

For case 0 and case 1 work like expected, but with default is throwed this error: 对于情况0和情况1可以按预期工作,但默认情况下会引发以下错误:

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

I can imagine that it occur because of $i, but how can I solve this problem? 我可以想象它是由$ i引起的,但是我该如何解决这个问题呢?

Thanks for help! 感谢帮助!

Most likely the query's failing to find anything and returning a zero-length node list. 查询很可能找不到任何东西,并返回零长度的节点列表。 Attempting to fetch a node from an empty list returns false, not an object. 尝试从空列表中获取节点将返回false,而不是对象。

Instead of assuming the query succeeded, use an intermediate holder to check: 而不是假设查询成功,请使用中间持有人进行检查:

$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'));
}

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

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