Tutorial on Simple XML (RSS) Manipulation with PHP
Published October 13th, 2006 in Small Talk, Tech-RamblingSomeone in a forum a week or two ago was asking about manipulating RSS feeds with simple PHP. I had not really done much with this, but I was definitely interested in it. Creating a PHP script which outputs a custom XML feed is not too hard, but it can be really redundant and time-consuming. Fortunately, grabbing the data from a feed is much easier and only requires a few lines of code. The main two functions are simplexml_load_file() and simplexml_load_string(). If you can access the file directly, you use the first function.
if ($xml = simplexml_load_file("http://blog.yourdomain.com/feed.xml")) {
$blog = $xml->channel;
$blogEntries = $blog->item;
echo "title = " . $blog->title . "\n";
}
?>
Many hosts block access to external files by direct access, so you have to use cURL to get around that problem. cURL allows you to read a file and return the contents into a string. If you couldn't guess, that's when the simplexml_load_string() function comes in play.
// cURL grabs the blog feed and puts it into $blogContents as a string
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://blog.yourdomain.com/feed.xml");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$blogContents = curl_exec($ch);
curl_close($ch);
// Done fetching feed, manipulate string
if ($xml = simplexml_load_string($blogContents)) {
$blog = $xml->channel;
$blogEntries = $blog->item;
echo '<a href="' . $blogEntries->link . '">' . $blogEntries->title . '</a>';
}
?>
Obviously, you would want to do a lot more error checking and have output messages for when the feed could not be accessed, but this gives you an idea of how easy simple XML manipulation can be.


I should mention this requires PHP5… but you should have upgraded by now anyway