Search code examples
phprssdomdocument

PHP DOMDocument Check if load() Is Valid


I am trying to load an RSS feed from my blog which I will then display on my home page. The PHP code I am using is:

$rss = new DOMDocument();
$rss->load('https://www.example.com/blog/feed');

However, sometimes my blog gets too busy and fails to return a valid feed, at which point I get:

DOMDocument::load(https://www.example.com/blog/feed): failed to open stream: HTTP request failed

How can I prevent getting that error so my script doesn't throw an exception? I'm looking for a way to check if the call to DOMDocument::load() is valid, e.g.:

if( $rss->load('https://www.example.com/blog/feed') ) {
    // Do something if call to load() is successful.
}

Solution

  • Do it in two steps. First get the XML, check that it's not empty, then load it into DOMDocument.

    $xml = file_get_contents('https://www.example.com/blog/feed');
    if ($xml) {
        $rss->loadXML($xml);
    } else {
        // report error
    }