sonia k sonia k - 6 months ago 18
PHP Question

Trying to get property of non-object when trying to echo the attribute of element

i keep getting error Trying to get property of non-object on the line

when running the script. i have the node and path correct but till not working

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


There is some javascript manipulation on that page that does the generation of <a>. But in essence (when you got the initial $html), there is none.

Here's a snippet of what you're getting from the initial lines of your code:

$url = "";    
$html = file_get_contents($url); <-- this one contains

This one:

<div class="info_coupon"> 
    <span rel="nofollow" data-lnu="aHR0cDovL3RyYWNraW5nLnZjb21taXNzaW9uLmNvbS9hZmZfYz9vZmZlcl9pZD0xMDIyJmFmZl9pZD0yMDYwJnVybD1odHRwcyUzQSUyRiUyRnBheXRtLmNvbSUyRiUzRnV0bV90ZXJtJTNEe2FmZmlsaWF0ZV9pZH0=" href="" 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)

So there is really no <a> after all.

But the data you're after is actually inside that <span>:


So just get it there:

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