I am developing web application for RSS feed automation using PHP.
Problem
in my module i adding link of rss and store in database then those link display to the user and when they click on link they can show the data of the link.
But sometime those link is not working so throws the following runtime exceptions:
Warning:
DOMDocument::load(http://webdesign.about.com/library /z_whats_new.rss%2Ccname=Web%20design%20about)
[domdocument.load]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in C:\xampp\htdocs\nf\showrss.php on line 59Warning:
DOMDocument::load()
[domdocument.load]: I/O warning : failed to load external entity"http://webdesign.about.com/library/z_whats_new.rss%2Ccname=Web%20design%20about"
in C:\xampp\htdocs \nf\showrss.php on line 59Fatal error: Call to a member function
getElementsByTagName()
on a non-object in C:\xampp\htdocs\nf\showrss.php on line 63
So how to handle this exception and display the user friendly message to user that your link is broken or not in valid rss format.
Following is the my php file to read the rss link.
ShowRss.php
<?php
$xml=$_GET["xml"];
$cname=$_GET['cname'];
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);
$channel=$xmlDoc->getElementsByTagName('channel')->item(0);
$channel_title = $channel->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$channel_link = $channel->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$channel_desc = $channel->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;
echo $cname;
echo("<p><a href='" . $channel_link
. "'>" . $channel_title . "</a>");
echo("<br>");
echo($channel_desc . "</p>");
$x=$xmlDoc->getElementsByTagName('item');
$c=$xmlDoc->getElementsByTagName('item')->length;
for ($i=0; $i<$c; $i++) {
$item_title=$x->item($i)->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$item_link=$x->item($i)->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$item_desc=$x->item($i)->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;
echo ("<p><h2><a href='" . $item_link
. "'>" . $item_title . "</a></h2>
echo ("<br>");
echo ($item_desc ."</p>");
}
}
?>
DOMDocument::load() returns false on failure, so you could do something like:
if ($xmlDoc->load($xml)) {
// work with the XML
} else {
// display an error message
}
This won't prevent the warnings from being raised, but it does allow you to handle the problem. Having the warnings could be useful to you, so you can see in your logs how often a resource you're depending on is failing.