Extracting an attribute with a SimpleXMLElement class

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
rodsem
Forum Newbie
Posts: 5
Joined: Mon May 16, 2005 1:21 am

Extracting an attribute with a SimpleXMLElement class

Post 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
mrcoffee
Forum Commoner
Posts: 31
Joined: Tue Nov 10, 2009 3:03 pm
Location: Wyoming, USA

Re: Extracting an attribute with a SimpleXMLElement class

Post by mrcoffee »

You can access attributes with SimpleXmlElement as an array.

Try:

Code: Select all

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