Page 1 of 1

PHP and RSS

Posted: Tue Jul 15, 2008 10:40 pm
by nrmstudios
~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.


:banghead: I was wondering if you could give me a little help with accessing the enclosure attributes in an RSS feed:

Code: Select all

 
<?php
 $xml=("http://www.christiantoday.com/rss/feed.xml?category=news-briefs");
 $xmlDoc = new DOMDocument();
 $xmlDoc->load($xml); 
 
 //get elements from "<channel>"
 $channel = $xmlDoc->getElementsByTagName('channel')->item(0); 
 $channel_title = $channel->getElementsByTagName('title')->item(0)->childNodes->item(0)->nodeValue;
 $channel_link  = $channel->getElementsByTagName('link')->item(0)->childNodes->item(0)->nodeValue;
 $channel_desc  = $channel->getElementsByTagName('description')->item(0)->childNodes->item(0)->nodeValue;
 
 //output elements from "<channel>"
 echo("<p><a href='" . $channel_link . "'>" . $channel_title . "</a>");
 echo("<br />");
 echo($channel_desc . "</p>");
 
 //get and output "<item>" elements
 $x = $xmlDoc->getElementsByTagName('item');
 for ($i=0; $i<=2; $i++)
 {
  $item_title=$x->item($i)->getElementsByTagName('title')->item(0)->childNodes->item(0)->nodeValue;
  $item_link=$x->item($i)->getElementsByTagName('link')->item(0)->childNodes->item(0)->nodeValue;
  $item_desc=$x->item($i)->getElementsByTagName('description')->item(0)->childNodes->item(0)->nodeValue; 
 
  // get enclosure info (url, length and type)
  $item_enURL = $x->item($i)->getElementsByTagName('enclosure')->item(0)->childNodes->item(0)->getAttribute('url');
  $item_enLEN = $x->item($i)->getElementsByTagName('enclosure')->item(0)->childNodes->item(0)->getAttribute("length");
  $item_enTYP = $x->item($i)->getElementsByTagName('enclosure')->item(0)->childNodes->item(0)->getAttribute("type");
  
  echo ("<p><a href='" . $item_link . "'>" . $item_title . "</a>");
  echo ("<br />");
  if(item_enURL != NULL){echo 'Enclosure is null.<br>';}
  echo ($item_desc . "</p>");
  
 }
?>


The error I get is:
Fatal error: Call to a member function getAttribute() on a non-object in C:\wamp\www\myfatherswork\rss.php on line 25

I think its just because there is no enclosure tag... is there an elegant way to test if the tags exist in the file? Thank you ahead a'time if you can give me any help.


~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.

Re: PHP and RSS

Posted: Wed Jul 16, 2008 9:48 am
by pickle
You can use the is_object() function to see if there's an object there.

Do you have PHP5? Using SimpleXML would be much...simpler.