PHP: handling SimpleXML errors

Some consuming web platforms, such as Twitter, offer a great opportunity to use the SimpleXML library to fetch results from remote using XML files. However, sometimes things go wrong and all you get is a bunch of errors. In the case of SimpleXML, this is mainly due to the fact that a web service may be down so that it cannot satisfy your request. In the case of Twitter, this happens too often. So one day you get your latest tweets or news and the other one you get a PHP warning containing (that's too bad) also some sensitive information about your PHP environment.

The PHP manual, as usual, provides very useful information about these particular problem. First of all, the simplexml_load_file() function returns false if an error has been risen. So the first, rough check you can run is to determine whether the request is successful or not:

$tweets = '';

if(simplexml_load_file($tweets)) {

  // continue


Furthermore, the PHP manual provides also a useful tip:

Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.

This is a really useful advice and I recommend you to follow this practice whenever you decide to use SimpleXML.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.