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('', false);
if($rss === false)
$feed = false;
$feed = mb_convert_encoding($rss, "HTML-ENTITIES", "UTF-8");
$result = new SimpleXMLElement($feed);
foreach($result->channel->item as $item)
$content = $item->children('');
$dom = new DOMDocument();
$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
//didn't work
//didn't work
//didn't work
//didn't work
//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.