在尝试回显元素的属性时尝试获取非对象的属性

时间:2016-04-26 03:34:09

标签: php html xpath domdocument

我不断收到错误试图获取非对象的属性  运行脚本时$title->$my_xpath->query。我有节点和路径正确,但直到不工作

    $nodes = $my_xpath->query( '//div[@class="info_coupon"]' );       
    foreach( $nodes as $node )
    {
        $title  = $my_xpath->query( 'a', $node )->item(0)->nodeValue;
        echo $title;
        $code = $my_xpath->query( 'a/@data-code', $node );
        if( $code->length>0 ) {
        $coupon = $code->item(0)->nodeValue ;
        echo $coupon;        
        }
    }

1 个答案:

答案 0 :(得分:0)

该页面上有一些javascript操作可以生成<a>。但实质上(当你得到最初的$html)时,没有。

以下是您从代码的初始行获得的内容片段:

$url = "http://zoutons.com/stores/paytm-coupons/";    
$html = file_get_contents($url); <-- this one contains

这一个:

<div class="info_coupon"> 
    <span rel="nofollow" data-lnu="aHR0cDovL3RyYWNraW5nLnZjb21taXNzaW9uLmNvbS9hZmZfYz9vZmZlcl9pZD0xMDIyJmFmZl9pZD0yMDYwJnVybD1odHRwcyUzQSUyRiUyRnBheXRtLmNvbSUyRiUzRnV0bV90ZXJtJTNEe2FmZmlsaWF0ZV9pZH0=" href="http://zoutons.com/stores/paytm-coupons/?#cid=31215" class="heading affiliate affiliate_map c_data_31215" data-affiliate="aHR0cDovL3RyYWNraW5nLnZjb21taXNzaW9uLmNvbS9hZmZfYz9vZmZlcl9pZD0xMDIyJmFmZl9pZD0yMDYwJnVybD1odHRwcyUzQSUyRiUyRnBheXRtLmNvbSUyRiUzRnV0bV90ZXJtJTNEe2FmZmlsaWF0ZV9pZH0="  data-id="31215" data-code="NEW50" data-link_type="text" store="Paytm">GET FREE Rs.50/- ON RECHARGE  (VALID TILL &#8211; APRIL 27)
    </span>

毕竟,确实没有<a>

但您之后的数据实际上在<span>

之内
href="http://zoutons.com/stores/paytm-coupons/?#cid=31215"
data-code="NEW50"

所以就这样吧:

$nodes = $my_xpath->query( '//div[@class="info_coupon"]' );       
foreach( $nodes as $node )
{
    $title = $my_xpath->evaluate('string(./span/@href)', $node);
    $code = $my_xpath->evaluate('string(./span/@data-code)', $node);
    echo $title;
    echo $code;
}