6CC001 Workshop - week 06
From mi-linux
Jump to navigationJump to searchMain Page >> Web Application Development >> Workbook >> Week 06
Today let’s play with RSS feeds. There are 2 things you can do:
- Consume an existing third-party feed
- Create your own feed, for other users to consume
Consume an existing third-party feed
Since PHP 5, consuming an XML file (remember that’s all an RSS feed is!) couldn’t be more simple:
$feed_url = "http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/front_page/rss.xml"; // Get data from feed file $response = file_get_contents($feed_url); // Insert XML into structure $xml = simplexml_load_string($response); // Browse structure foreach($xml->channel->item as $one_item) echo $one_item->title."<BR>";
First you load the content of the remote file into a variable, using the file_get_contents function.
Then you concert this big blob of data into a more friendly, loop-able structured object, using the simplexml_load_string function.
And finally, you loop through your object and display the data on the screen. This example only displays the title of the different articles. Note: You might want to improve this part (items in a list, clickable links etc…)
Create your own feed, for other users to consume
// Connect to database // Get latest items from db $sql = "SELECT title FROM messages ORDER BY date_added DESC limit 0,10"; $rst = mysql_query($sql); // Loop through data $items = ""; while($a_row = mysql_fetch_assoc($rst)) { $items.= "<item>"; $items.= " <title>{$rst['title']}</title>"; $items.= " <link>http://www.dude.com/</link>"; $items.= " <description>A cool article</description>"; $items.= "</item>"; } $feed = "<?xml version=\"1.0\"?>"; $feed.= "<rss version=\"2.0\">"; $feed.= " <channel>"; $feed.= " <title>My cool feed</title>"; $feed.= " <link>http://www.dude.com/</link>"; $feed.= " <description>A cool feed</description>"; $feed.= " $items"; $feed.= " </channel>"; $feed.= "</rss>"; echo $feed;