English 中文(简体)
在PHP中,DOMNode的Attribute()在DOMXPath query中变数。 为什么?
原标题:getAttribute() of DOMNode in PHP doesn t work with a variable in DOMXPath query. Why?

我有这项方案,有了一个开关:

$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

我可以想象,这是因为一美元而发生的,但我如何能够解决这一问题?

帮助!

最佳回答

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.

不是接手盘问,而是使用中间持有人检查:

$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 ));
}
问题回答

暂无回答




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签