Anthems
Anthems

Reputation: 1

How to check if namespace element exists in PHP

I'm trying to check if the element media:content exists so that a thumbnail image can be shown from an rss feed but not sure how to validate it's existence.

I can get the media:content url and show the image fine but checking to see if it exists isn't working out. I've tried isset and defined but I'm clearly doing something wrong.

Main line i'm concerned about below is:

if(defined($item->getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'content')->item(0)->getAttribute('url')))

<?php
$feed = new DOMDocument();
$feed->load('http://rss.cnn.com/rss/cnn_topstories.rss');
$json = array();
$items = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('item');
$json['item'] = array();
foreach($items as $item) {
 $title = $item->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
 $description = $item->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
 $text = $item->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
    if(defined($item->getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'content')->item(0)->getAttribute('url'))){
        $image = $item->getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'content')->item(0)->getAttribute('url');
    }
    else{
        $image = '';
    }
    echo $image;
}
?>

Upvotes: 0

Views: 1160

Answers (2)

Anthems
Anthems

Reputation: 1

Nigel was right, using ->length is the way to do it.

if($item->getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'content')->length > 0){
            $image = $item->getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'content')->item(0)->getAttribute('url');
}

Upvotes: 0

Nigel Ren
Nigel Ren

Reputation: 57121

When you use getElementsByTagName, this always returns a DOMNodeList. The main thing is to check if the node list has 0 elements.

So rather than defined() or isset(), use ->length...

$nodes=$domDocument->getElementsByTagName('book') ; 
if ($nodes->length==0) { 
   // no results 
} 

( Example from http://php.net/manual/en/domdocument.getelementsbytagname.php)

Upvotes: 0

Related Questions