www.webdeveloper.com
Results 1 to 2 of 2

Thread: Extracting an attribute with a SimpleXMLElement class

  1. #1
    Join Date
    Sep 2011
    Location
    El Salvador
    Posts
    2

    Extracting an attribute with a SimpleXMLElement class

    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:
    <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:
    <?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:
    <?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

  2. #2
    Join Date
    Jul 2010
    Location
    /ramdisk/
    Posts
    865
    Since attributes are unique to each element they can be expressed in an array. Infact, the simpleXMLelement class implements ArrayAccess if I recall correctly.

    <enclosure url="http://www.thedomain.com/theimage.jpg" length="17800" type="image/jpeg"/>

    Would be:

    $enclosure['url'];

    BUT, you will want to check it with isset() first. It might not be there.
    I use (, ; : -) as I please- instead of learning the English language specification: I decided to learn Scheme and Java;

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles