PHP DOMDocument stops render on errors

Several of PHP’s DomDocument functions halt rendering the page on any kind of error, and are finicky to test. I was parsing an RSS feed and wanted to display a scaled down version of the image in the feed. This code worked if the code contained an image:
$rss = @file_get_contents('http://problemstosolve.com/?feed=rss2', false);
if($rss === false)
{
$feed = false;
}else
{
$feed = mb_convert_encoding($rss, "HTML-ENTITIES", "UTF-8");
}
$result = new SimpleXMLElement($feed);
foreach($result->channel->item as $item)
{
$content = $item->children('http://purl.org/rss/1.0/modules/content/');
$dom = new DOMDocument();
$dom->loadHTML($content->encoded);
$images = $dom->getElementsByTagName('img');
echo "<img src=\"" . $images->item(0)->getAttribute('src') . "\" width=\"100\" /><br/>";
}

However, if the post didn’t contain an image, the whole page would blow up with no PHP error. To make things worse, if the problem was in one of several codeigniter views, it would make codeigniter display the views out of order. None of these tests for images worked:

//didn't work
if(!$images)
//didn't work
if(!empty($images))
//didn't work
if(!empty($images->hasAttribute('src')))
//didn't work
if(!empty($images->item(0)))
//didn't work
if(!$images->children)
//didn't work
if($images->length() == 0)

What finally worked was:
if($images->length == 0)

getElementsByTagName always returns a DOMNodeList and it’s hard to check to see if it actually contains anything. I haven’t figured out a way for PHP to handle errors better with DOMDocument.

Trackback this Post | Feed on comments to this Post

Leave a Reply

You must be logged in to post a comment.