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

1.6k views Asked by At

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:

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?

Thanks for help!

1

There are 1 answers

1
Marc B On BEST ANSWER

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.

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