Page 1 of 1

Extracting an attribute with a SimpleXMLElement class

Posted: Tue Sep 27, 2011 4:44 am
by rodsem
Hi guys, and thanks for you help in advance. I would appreciate if you can help me with this code:

I have an XML with this structure:

Code: Select all

<item>
<title><![CDATA[Here is the title of the item]]></title>
<link><![CDATA[http://www.thedomain.com]]></link>
<description><![CDATA[The content of the item]]></description>
<enclosure url="http://www.thedomain.com/theimage.jpg" length="17800" type="image/jpeg"/>
</item>
And I have this function to read it:

Code: Select all

<?php
function getFeed($feed_url) {
	$content = file_get_contents($feed_url);
	$x = new SimpleXmlElement($content);
	echo "<ul>";
	foreach($x->channel->item as $entry) {
		echo "
		<li>
		  <a href='$entry->link' title='$entry->title' target='_blank'>" . $entry->title . "</a>
		</li>";
		}
	echo "</ul>";
}
?>
My problem is that I don't know how to get the image from the "enclosure" tag on the XML. I have tried to use the "attributes" function but it seems that I don't know how to use it because it's just not working. Can anybody tell me what would be the right code to pull the image and use as follow (look for "THE-IMAGE-HERE" in the next code):

Code: Select all

<?php
function getFeed($feed_url) {
	$content = file_get_contents($feed_url);
	$x = new SimpleXmlElement($content);
	echo "<ul>";
	foreach($x->channel->item as $entry) {
		echo "
		<li>
		  <a href='$entry->link' title='$entry->title' target='_blank'><img src='THE-IMAGE-HERE'>" . $entry->title . "</a>
		</li>";
		}
	echo "</ul>";
}
?>
Thanks in advance

Re: Extracting an attribute with a SimpleXMLElement class

Posted: Tue Sep 27, 2011 1:05 pm
by mrcoffee
You can access attributes with SimpleXmlElement as an array.

Try:

Code: Select all

$entry->enclosure['url']
Hope that helps.